React Reload Instantly on Messaging

Viewed 177

I made messaging app. I used Django for the backend and React for the frontend. When I write a message and click to send button I can save the message but I need to refresh the page to display this message on messaging field. I want to display this message instantly then click the button.

When I write a message and click to send button I'm getting the message text and save it into Django with Fetch-Post method.

In the messaging area I'm getting all messages with Fetch - GET method and I'm saving all of them into the Conversation state. Then I'm displaying all messages with {messages}

Send message:

  const send_message= (e, data) => {

    e.preventDefault();

    fetch('http://localhost:8000/api/messages/', {
      method: 'POST',
      headers: {
        Authorization: `JWT ${localStorage.getItem('token')}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({conversation: selectedMesaj.conversation, sender: username, msg_content:  inputfield, reciepent: [`${selectedMesaj.sender}`], })
    })
      .then(res => res.json())
      .then(json => {
        setGonderMesaj(json.id);
      });


  };

Get all messages:

  useEffect(() => {
    fetch("http://localhost:8000/api/messages/",{
      method:'GET',
      headers: {
        'Content-Type':'application/json',
        'Authorization': `JWT ${localStorage.getItem('token')}`
      }
    })
    .then( res => res.json())
    .then( resp => setMessages(resp))
    .catch( error => console.log(error))
  }, [])

Display all messages:

{messages}

It works but my issue is to imagine sending a message while talking on Whatsapp and you have to refresh the page for the message you sent or the message you sent to appear. I want the message to appear instantly on the screen as soon as it is sent or received.

I don't know how to handle it but I think must use API because I built this messaging app with Django Rest framework.

I'm waiting for your answers. I really don't know how to solve this issue.

1 Answers

have you tried to put massages in the empty array in useEffect? window.location.reload(); - will reload the page but if you want to re-render you can just fire update with props/state.

Related