Answers for "fetching data using useeffect"

1

fetch with useEffect hook

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

const User = () => {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    getUsers();
  }, []);

  async function getUsers() {
    const response = await fetch('https://jsonplaceholder.typicode.com/users');
    const users = await response.json();
    setUsers(users);
  }

  return (
    <ul>
      {users.map(user => (
        <li>{user.name}</li>
      ))}
    </ul>
  );
};

export default User;
Posted by: Guest on August-25-2021
1

DATA FETCHING IN EFFECT HOOK

const useDataApi = (initialUrl, initialData) => {
  const [url, setUrl] = useState(initialUrl);
 
  const [state, dispatch] = useReducer(dataFetchReducer, {
    isLoading: false,
    isError: false,
    data: initialData,
  });
 
  useEffect(() => {
    let didCancel = false;
 
    const fetchData = async () => {
      dispatch({ type: 'FETCH_INIT' });
 
      try {
        const result = await axios(url);
 
        if (!didCancel) {
          dispatch({ type: 'FETCH_SUCCESS', payload: result.data });
        }
      } catch (error) {
        if (!didCancel) {
          dispatch({ type: 'FETCH_FAILURE' });
        }
      }
    };
 
    fetchData();
 
    return () => {
      didCancel = true;
    };
  }, [url]);
 
  return [state, setUrl];
};
Posted by: Guest on October-14-2021
0

how to fetch data with useEffect

useEffect(() => {
    const fetchData = async () => {
      const result = await fetch(
        'https://my-api.com',
      );
 
      setState(result);
    };
 
    fetchData();
  }, []);
Posted by: Guest on April-10-2021

Code answers related to "fetching data using useeffect"

Code answers related to "Javascript"

Browse Popular Code Answers by Language