skip to Main Content
let initialData = {
 products:[]
}

const ItemReducer = (state = initialData, action) => {
  switch (action.type) {
    case "FETCHDATA":
      return {
        ...state,
        products: action.payload,
      };
  }
 return state;
}


let [productdata, setProductdata] = useState();
  const dispatch = useDispatch();
useEffect(()=>{
  axios.get("https://fakestoreapi.com/products")
  .then((res) => setProductdata(res.data))
  .catch((err) => console.log("error"))
},[]);
dispatch({type:"FETCHDATA",payload: productdata});

Initial state of ItemReducer must contain the "product details" which needs to be fetch from api call. While am using the above code, its returning undefined.

2

Answers


  1. One possibility is to do the fetch in a parent component and only render the children (that has the useDispatch) when the productData is present. That way it can also handle error and loading states, something like this:

    const ProductDetailsList = ({ products }) => {
      const dispatch = useDispatch();
    
      useEffect(() => {
        dispatch({ type: "FETCHDATA", payload: products });
      }, [dispatch])
    
      return <div>...</div>;
    };
    
    const ProductsDetails = () => {
      const [products, setProducts] = React.useState([])
      const [loading, setLoading] = React.useState(false)
      const [error, setError] = React.useState(null)
    
      useEffect(() => {
        setLoading(true)
        axios
          .get("https://fakestoreapi.com/products")
          .then((res) => setProducts(res.data))
          .catch(setError)
          .finally(() => setLoading(false))
      }, []);
    
      if (loading) {
        return <div>Loading...</div>
      }
    
      if (error) {
        return <div>Error: {error.message}</div>
      }
    
      return <ProductDetailsList products={products} />
    }
    
    Login or Signup to reply.
  2. Related to the docks you have to use

    fetch('https://fakestoreapi.com/products')
            .then(res=>res.json())
            .then(json=>console.log(json))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search