“async useeffect” Kode Jawaban

cara menggunakan async menunggu di dalam evefeffect

useEffect(() => {
    async function fetchData() {
        try {
            const response = await fetch(
                `https://www.reddit.com/r/${subreddit}.json`
            );
            const json = await response.json();
            setPosts(json.data.children.map(it => it.data));
        } catch (e) {
            console.error(e);
        }
    };
    fetchData();
}, []);
Red Team

async useeffect

const [users, setUsers] = useState([]);
  
useffect(() => {
  const getUsers = async () => {
    let response = await fetch('/users');
    let data = await response.json();
    setUsers(data);
  };
    
 getUsers();
}, []);
Julio Polycarpo

async useeffect

useEffect(() => {
  (async function anyNameFunction() {await loadContent();})();
}, []); 
Jittery Jaguar

async useeffect

 function OutsideUsageExample() {
  const [data, dataSet] = useState<any>(null)

  const fetchMyAPI = useCallback(async () => {
    let response = await fetch('api/data')
    response = await response.json()
    dataSet(response)
  }, [])

  useEffect(() => {
    fetchMyAPI()
  }, [fetchMyAPI])

  return (
    <div>
      <div>data: {JSON.stringify(data)}</div>
      <div>
        <button onClick={fetchMyAPI}>manual fetch</button>
      </div>
    </div>
  )
}
Embarrassed Echidna

async useeffect

function Example() {
  const [data, dataSet] = useState<any>(null)

  useEffect(() => {
    async function fetchMyAPI() {
      let response = await fetch('api/data')
      response = await response.json()
      dataSet(response)
    }

    fetchMyAPI()
  }, [])

  return <div>{JSON.stringify(data)}</div>
}
Reza

Jawaban yang mirip dengan “async useeffect”

Pertanyaan yang mirip dengan “async useeffect”

Lebih banyak jawaban terkait untuk “async useeffect” di JavaScript

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya