The issue I am having is in the change() function. I want to call filteredData() function after the setState runs. Usually, I would use a callback function to call filteredData, but useState doesn't allow callbacks. I can't use useEffect because it will call the function initially before there is any data change.
import React, { useState, createContext, useEffect } from "react";
import data from "../Reducers/ListingsData";
export const GlobalContext = createContext();
export function GlobalProvider({ children }) {
const [state, setState] = useState({
name: "",
city: "all",
homeType: "all",
rooms: 0,
bathrooms: 0,
min_price: 0,
max_price: 10000000,
min_floor_space: 0,
max_floor_space: 40000,
finished_basement: false,
swimming_pool: false,
garage: false,
data: data,
filteredData: data,
populateFormsData: "",
sortby: "price-dsc",
search: "",
});
function change(event) {
let name = event.target.name;
let value =
event.target.type === "checkbox"
? event.target.checked
: event.target.value;
setState((prevState) => ({ ...prevState, [name]: value }));
filteredData();
}
function filteredData() {
console.log(state);
}
return (
<GlobalContext.Provider value={{ state: state, change }}>
{children}
</GlobalContext.Provider>
);
}