Skip to content
Advertisement

How to better setup fetch with useEffect?

Im learning JS and React and I came to the code example below and some parts I don’t understand properly. The second .then is inside useUffect is this ok, or it’s better to be in getData func? Also in render there is data**?**.map and I don’t understand why we need ?, is this ternary operator? Is so I thought that ternary operator requires : as a second parameter. Thanks in advance!

import React, { useState, useEffect } from "react";

const FetchData = () => {
  const [data, setData] = useState(null);
  const fetchURL = "https://jsonplaceholder.typicode.com";
    
    const getData = () => fetch(`${fetchURL}/posts`)
        .then((res) => res.json());

    useEffect(() => {
        getData().then((data) => setData(data));
    }, []);

    return (<div>
        {data?.map(item => (
            <ul>
                <li>{item.title}</li>
          </ul>
      ))}
  </div>);
};

export default FetchData;

Advertisement

Answer

I think, your code is fine, Move getData and fetchURL into useEffect incase if there’s any error.

Also, You can simply use async/await approach for the same.

import React, { useState, useEffect } from "react";

const FetchData = () => {
  const [data, setData] = useState(null) // here you can define `[]` if you don't want to check `?`
  useEffect(() => {
    const fetchURL = "https://jsonplaceholder.typicode.com";
    const getData = async () => {
      const res = await fetch(`${fetchURL}/posts`)
      const result = await res.json();
      setData(result);
    }
    getData()

  }, []);

    return (<div>
        {data?.map(item => (
            <ul>
                <li>{item.title}</li>
          </ul>
      ))}
  </div>);
};

export default FetchData;

? is Called Optional Chain Operator, which will help you to check whether the value is nullish (null or undefined).

Basically, it just doing if (data) { data.map...}

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement