简体   繁体   中英

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;

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...}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM