0

I currently have a project and I need to pass the array to another component for my search bar. I am using React's Context.

I've tried passing my data but I seem to get an undefined value in my console.

Code in Context.js

Export const SearchContext = createContext();

This is the code in MainPage.js:

const data = [json_1, json_2];

const array = data.map(values => {
 const search = _.flattenDeep(values);
 values.search = search;
 return values;
})

<SearchContext.Provider value={array} />

and in my Searchbar.js

const options = useContext(SearchContext);

console.log(options);

<AutoComplete
                                className="searchbar"
                                placeholder="Search..."
                                dataSource = {options}
                                onfilterOption={(inputValue, option) =>
                                    option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1
                                  }
                        />

In the console.log I get an undefined value. This data should also be able to populate my search bar.

3
  • 1
    <SearchContext.Provider value={array} /> if this is the exact line you have then you aren't wrapping your consumer inside the context it is going to consume Commented Jul 29, 2019 at 4:27
  • So should I put the array inside the context provider instead of putting it inside the value? Commented Jul 29, 2019 at 4:30
  • 1
    Make sure your SearchBar is a child of SearchContext.Provider Commented Jul 29, 2019 at 4:31

1 Answer 1

1

please look at this Gist : https://gist.github.com/nimahkh/9c008aaf2fd2d1cc83cd98c61e54979a


you have to wrap your component with Provider and inside of that component that is Wrapped , you have access to value , it's impossible to fetch value , out of the box

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

Comments

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.