my state change when I set it, but my other component which use this state value through the react context don't show the state with the new result
I have a state being declared inside a context provider and one component A set this state and other component B just read... but when I change the state with the component A, the component B doesn't show the new value, keep showing the initial value! how I solve that, please?
context file:
export const SearchContext = React.createContext();
export const SearchProvider = (props) => {
const [searchInput, setSearchInput] = useState({
content: "Matrix", });
return (
<SearchContext.Provider value=>
{props.children}
</SearchContext.Provider>
);
};
form component(component A in the question):
export default () => {
const history = useHistory()
**const {searchInput, setSearchInput} = React.useContext(SearchContext);**
function search (e) {
e.preventDefault();
history.push('/resultado-de-busca')
const searchContent = document.querySelector(`[data-input-search]`).value;
setSearchInput({...searchInput, content:searchContent })
}
return (
<form className="search" data-search onSubmit={search}>
<input data-input-search placeholder="Digite o nome desejado..." type="text" />
</form>
);
};
page component (component B in the question, where is rendered the result):
const {searchInput} = React.useContext(SearchContext);
console.log(searchInput.content):
// results: 'Matrix' instead of the new value changed in Component A
component B is called inside the App.js from React, and inside the SearchProvider that way:
<SearchProvider>
<SearchPage/>
</SearchProvider>
Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW
Comments
Post a Comment