Trying to learn how to use react hooks. I use createContext and I want to transfer together state and a function to other components, but I need help with how to do this. I also want to ask if it makes sense to do so.
In fact, I can update state by using setState in my case, but by defining a function in context, I think it makes more sense to use this function anywhere. Am I wrong ?
my context is :
export const ExpenseContext = createContext();
export const ExpenseProvider = props => {
const [expense, setExpense] = useState(initialExpenses)
const clearItems = () => {
setExpense([])
}
return ( <
ExpenseContext.Provider value = {
[expense, setExpense],
clearItems
} > {
props.children
} <
/ExpenseContext.Provider>
)
}
The component I want to use this function :
const ExpenseList = () => {
const [expense, setExpense] = useContext(ExpenseContext);
const {
clearItem
} = useContext(ExpenseContext);
// const clearItems = () => { normally this works ı know!
// setExpense([])
// }
return ( <
>
<
List > {
expense.map((expense) => {
return <Item key = {
expense.id
}
expense = {
expense
}
/>;
})
} <
/List> <
div className = "text-center" > {
expense.length > 0 && ( <
Button onClick = {
clearItems
}
type = "danger"
shape = "round"
icon = { < DeleteOutlined / >
} >
Clear Expenses <
/Button>
)
} <
/div> < /
>
);
};
in this case, it is possible to use this function directly within the component without trying to transfer the function. But what I'm curious about is how I can manage to transfer and receive functions.
Note: when I try to use it in this way, I get this error: TypeError: Object is not a function
const [searchTerm, setSearchTerm] = useState(""); const value = {searchTerm, setSearchTerm }; <UserProvider value={value}>
and then use it likeconst { searchTerm, setSearchTerm } = useContext(UserContext);