0

My app renders messages. App fetches messages from API and save it in state. Provide you my component code:

const MessagesScreen = () => {

     const [messages, setMessages] = useState([]);

     useEffect(() => {
        getMessages();
        processMessages();
      }, []);

      async function getMessages() {
         try {
        
            let request = {
                token: auth,
                offset: offset,
                limit: limit,
            };
    
            const response = await network('my URL API', request);

            
            setMessages([...messages, ...response]); // or even setMessages(response);

            console.log(response);// IS NOT EMPTY, FILLED WITH DATA FROM API
            console.log(messages);  // IS EMPTY [], BUT I JUST CALLED setMessages BEFORE
   

          }
          catch (err) {
             console.log(err)
          }
        }

        function processMessages() {
             console.log(messages);  // IS EMPTY [], BUT I NEED TO PROCESS MESSAGES
             ...
        }

        return (<FlatList data={messages}/>)
}

As you can see, messages is empty array everywhere. How can I fix it? Please, help!

Alexey
  • 13
  • 2

1 Answers1

1

From docs https://legacy.reactjs.org/docs/react-component.html#setstate setState() does not always immediately update the component. It may batch or defer the update until later. This why your console.log(messages) is showing an empty array

Aakash Rathee
  • 523
  • 3
  • 17