V
V
VloVer2020-07-11 16:58:13
React
VloVer, 2020-07-11 16:58:13

UseState React not updating data?

const [lists, setLists] = useState(null);

useEffect (() => {
      async function getUser() {
         try {
           const response = await axios.get('http://localhost:3001/lists');
           const {data} = response;
           setLists(data);
           console.log(lists);
         } catch (error) {
           console.error(error);
         }
       }
       getUser() 
      axios.get('http://localhost:3001/lists').then(({ data }) => {
         let list = data;
         setLists(list);
      });
   }, [])


I want to get data from the server, I use json-server, I use the axios library to get it, then I need to pass lists to another component, and then sort through the map and render it, but it gives the error 'Cannot read property 'map' of null', this is understandable, because the state is not updated, and in the null sheet, I displayed the list in another component is also null, tell me where the error is, sorry if it is banal, but in react not so long ago ...

I tried both with async / await and without him, the result is the same

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-07-11
@VloVer

The data request is asynchronous, so rendering with lists equal to null will still be done. And here, where you are trying to iterate over lists, check that it is not null - then you can call map. Or set the default value to an empty array instead of null.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question