0

i want to update the context form a response using axios so i can use it in another component on another page

const search = (min, max, l, r) => {
    if (min == null) min = 0;
    if (max == null) max = 2000000;
    if (l === "") l = "Tirane";
    if (isNaN(r)) r = 0;
    axios
      .get("/////", {
        params: {
          MaxValue: max,
          MinValue: min,
          city: l,
          rooms: r,
        },
      })
      .then((response) => {
        console.log(response.data);
        setSearchData(response.data);
        console.log(searchData);
      })
      .catch(function (error) {
        console.log(error);
      });
  };
export const SearchContext = createContext();

export const SearchProvider = (props) => {
  const [searchData, setSearchData] = useState([]);

  return (
    <SearchContext.Provider value={[searchData, setSearchData]}>
      {props.children}
    </SearchContext.Provider>
  );
};

when i console the searchData it displays an empty array.

1 Answers1

1

First, you have to add some data fetching logic in your SearchProvider component.

export const SearchProvider = (props) => {
  const [searchData, setSearchData] = useState([]);

  // do not forget to add useEffect hook import
  useEffect(async () => {
      const { data } = await axios
          .get("/////", {
            // add your params
           },
         })

    setSearchData(data);
  });

  return (
    <SearchContext.Provider value={[searchData, setSearchData]}>
      {props.children}
    </SearchContext.Provider>
  );
};

You can use SearchContext.Consumer in another component where you want to get your values and implement data fetching there.

<SearchContext.Consumer>
    {([searchData, setSearchData]) => {}}
</SearchContext.Consumer>

There you have to implement some data fetching mechanics, and call

vicacid
  • 509
  • 4
  • 6