React: How do I move my ajax api call into a separate component? React: How do I move my ajax api call into a separate component? reactjs reactjs

React: How do I move my ajax api call into a separate component?


You need to return fetch(url) itself, so you'll return a promise and then you can use then method:

const API = 'https://randomuser.me/api/?results=5';export function fetchProfiles() {  let url = API;  // return the promise itself  return fetch(url).then( (res) => res.json() );}


The way I fixed this was to return fetch(url) itself:

const API = 'https://randomuser.me/api/?results=5';export function fetchProfiles() {    let url = API;    return fetch(url)      .then( (response) => response.json() );}

Then in the container component:

    componentDidMount() {      fetchProfiles()        .then( (data) => {          let results = data.results;          this.setState({            profiles: results          });        });    }

This now works!!


I once made a similar app that i separated the API calls from the context (i used context API btw) instead of returning the fetch function and handle the async calls on the context, i handled everything on the function declared on the API and on the context only recieved the result, this seems to be a little bit more complicated but it simplifies the data handling on the context and all the data fetching login on the other side, i also used axios for the API call but it's easily swapped with the fetch one (axios handles better errors like handling of timeouts or service not available)

on profiles.js:

import axios from 'axios';const API = 'https://randomuser.me/api/?results=5';    export const fetchProfiles = async () => {    let url = API;    try{      const response = await axios.get(url)      const data = response.data      return data    }catch(error) {      console.log('failed to fetch Profiles')      throw Error(error)    }}

on the context:

import { fetchProfiles} from "../API/profiles";const getProfiles = async () =>{  const result = await fetchProfiles();  this.setState({    profiles: result  });}