Skip to content
Advertisement

Trying to fetch APi but it is not displaying the data

I have created Context API I am trying to fetch the data from my API so I can use the state globally, but is not doing it. I am not getting any errors in the console. But when I try to fetch from the Other Component, I am getting data in the console. Just in the Context, I am not getting it.

import React, {useState, useEffect}from 'react'
import ITrucks from '../interface/truck';
import axios from 'axios';

export const TrucksContext=  React.createContext({})

export const TrucksProvider:React.FC = ({ children }  ) => {

const [isLoading, setIsLoading] = useState(false);
const [trucks, setTrucks] =useState<ITrucks[]>([])
const [isError, setIsError] = useState(false);
const fetchData = () => {
  axios
    .get('https://localhost:7000/trucks')
    .then((response) => {
      setIsLoading(false);
      setTrucks(response.data);
      console.log(response.data)
    })
    .catch((error) => {
      setIsLoading(false);
      setIsError(true);
      console.log(error);
    });
};
useEffect(() => {
  fetchData();
}, []);
   


  return (

  
    <TrucksContext.Provider
      value={{trucks}}
    >
    <>
      {children}
      </>
    </TrucksContext.Provider>
  );
}

Advertisement

Answer

try setTrucks([...response.data])

Advertisement