D
D
Dmitry Samoilov2021-10-31 11:08:40
React
Dmitry Samoilov, 2021-10-31 11:08:40

Map does not work on received data from the server, how to fix it?

Hello, I can’t figure out the problem, the map function does not work with the data that I receive from the server. I write in React, use axios to get data and wrap it in useEffect so that the data is loaded during component rendering. According to the idea, the data is loaded normally, it turned out to display, it means that the problem is not in the map 617e4d5872e85732371479.jpeg
But after reloading it gives an error 617e4d910de9f244316975.jpegThis is probably because the data does not have time to be loaded from the server to start the search, but I don’t understand why .. Like useEffect and async await should decide this problem, the code must wait for this data, and then work with it, so what's the problem? I don't understand how to fix it, in another component I have the same code, but everything works well there, here is the code

const [fullPost, setFullPost] = useState([]);
  const { id } = useParams();

  useEffect(() => {
    const fetchFullPost = async () => {
      const res = await axios.get('/posts/' + id);
      setFullPost(res.data);
    };
    fetchFullPost();
  }, [id]);

  const cat = fullPost.categories.map((e) => e.name);
  const body = fullPost.body.map((e) => e.blocks)[0];

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Samoilov, 2021-10-31
@distCom

I solved it with conditional rendering, it seems to work

{fullPost.length === 0 ? (
        'Загружается'
      ) : (
        <FullPostContent fullPost={fullPost} />
      )}

A
Alexey Ukolov, 2021-10-31
@alexey-m-ukolov

useState({categories: [], body: []});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question