2

I'm trying to pass data with Context API to child components. Value is getting undefined upon fetching it from a component.

Component Hierarchy:

  • passing data to a component MockTable and UsecasePane
  • MainContent -> MockTable
  • MainContent -> AddMock -> TabContent -> UsecasePane

=> MockContext.js

import React, { useState, useEffect, createContext } from "react";
import axios from "axios";

export const MockContext = createContext();

// provider
export const MockProvider = (props) => {
  const [data, setData] = useState([]);
  
   // data fetch and setting the state

  return (
    <MockContext.Provider data={[data, setData]}>
      {props.children}
    </MockContext.Provider>
  );
};

  • Note: I'm getting response from the API.

Now in MainContent, components are encapsulated as follows:

// MainContent.js

import React from "react";
import { MockProvider } from "../MockContext";

const MainContent = () => {
  return (
    <MockProvider>
      <div>
        <CustomerTable />
        <AddMock />
        <MockTable />
      </div>
    </MockProvider>
  );
};

When I try to fetch the data in MockTable or in UseCasePane, value is undefined.

// MockTable.js

import React, { useState, useEffect, useContext } from "react";
import { MockContext } from "./MockContext";

const MockTable = () => {

  const [data, setData] = useContext(MockContext);
  console.log(data);

  // rest of the code

}

Please correct me where I'm going wrong :)

I tried to pass a String as well from the context and fetched in a component like:

return (
    <MockContext.Provider data={"Hello"}>
      {props.children}
    </MockContext.Provider>
  );

// in MockTable.js
const value = useContext(MockContext); ==> undefined
6
  • There was no error right? Commented Aug 6, 2020 at 9:08
  • 1
    What is undefined? You're logging data1 instead of data? Commented Aug 6, 2020 at 9:09
  • @AyushWalia: There is error. It will shows object is not iterable since the value is undefined Commented Aug 6, 2020 at 9:10
  • @codemax: sorry! typo. Please check again :) Commented Aug 6, 2020 at 9:12
  • Is response.data an array and was it set correctly in the <MockProvider />? Commented Aug 6, 2020 at 9:13

1 Answer 1

3

The correct prop to pass into the Provider is value, not data. (See: Context.Provider)


import React, { useState, useEffect, createContext } from "react";
import axios from "axios";

export const MockContext = createContext();

// provider
export const MockProvider = (props) => {
  const [data, setData] = useState([]);
  const fetchData = async () => {
    const response = await axios
      .get(config.App_URL.getAllRoute, {
        params: {
          customHostName: config.host,
          type: config.type,
        },
      })
      .catch((error) => {
        console.error(`Error in fetching the data ${error}`);
      });
    console.log(response.data);
    setData(response.data);
  };
  useEffect(() => {
    fetchData();
  }, []);

  return (
    <MockContext.Provider value={[data, setData]}>
      {props.children}
    </MockContext.Provider>
  );
};

Sign up to request clarification or add additional context in comments.

2 Comments

I suggest cleaning up the code block to only the line(s) that matters. The answer currently contains a lot of noise since you copied the whole code block but only changed one thing. I would show only the <MockContext.Provider value={...}> line, or the whole return statement. Everything above the return statement only makes the answer less readable imo.
Thanks @codeMax :) and 3limin4t0r for your suggestions. i'll clean up the code block

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.