简体   繁体   中英

Fetch data from api in createContext using Fetch api in React doesn't work

I have an existing context for products. Where initially I used some mock data as shown below STORE_DATA to render the components. Now I need to replace that mock data and connect to a Node.js api which is available on my local port (created the api I after I created the react-app ).

import React, { createContext, useState } from 'react';
import STORE_DATA from '../shop';

export const ProductsContext = createContext();

const ProductsContextProvider = ({ children }) => {
const [products] = useState(STORE_DATA);

return (
  <ProductsContext.Provider value={{ products }}>
    {
      children
    }
  </ProductsContext.Provider>
 );
}

export default ProductsContextProvider;

Just created a helper.js file witht he following to fetch the data:

 import {useEffect} from "react";


const fetchData = () => {
    return fetch("https://localhost:8081/products") <<tested on postman and works fine.
          .then((response) => response.json())
          .then((data) => console.log('Fetching Data:',data));
}

How to replace the mock data on the context file and use this fetchData() using useEffect within the context ? What code should change?

Tried the following, but didn't work, can't even print the console.log :

import React, { createContext, useState, useEffect } from 'react';
import { fetchData } from '../helpers';

export const ProductsContext = createContext();

const ProductsContextProvider = ({ children }) => {
  const [products, setProducts] = useState(null);

  useEffect(() => {
    setProducts(fetchData());
    }, []);

  return (
    <ProductsContext.Provider value={{ products }}>
      {
        children
      }
    </ProductsContext.Provider>
  );
}

export default ProductsContextProvider;

The issue was that it was returning the following error ( explained ):

net::ERR_SSL_PROTOCOL_ERROR (on chrome)

Solution: Use http:// instead of https:// in the URL's in the following code:

const fetchData = () => {
    return fetch("http://localhost:8081/products") 
          .then((response) => response.json())
          .then((data) => console.log('Fetching Data:',data));
}

CORS issue. Try putting header for CORS: Refer to this link for clear answer: https://stackabuse.com/handling-cors-with-node-js

Without CORS Setting, your Reactjs API will be blocked, You can check console for the same. it will throw: net::ERR_FAILED

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM