I get an error when I delete some lead(item). It deletes from the database but not from UI and gives this error dispatch is not a function.
//lead.js from /action
export const deleteLead = (id) => {
return (dispatch) => {
axios
.delete(`/api/leads/${id}/`)
.then((res) => {
dispatch({
type: DELETE_LEAD,
payload: id,
});
})
.catch((err) => console.log(err));
};
};
//Frontend file
import { getLeads, deleteLead } from "../../actions/leads";
<button
onClick={deleteLead(lead.id)}
className="btn btn-danger btn-sm">
Delete
</button>
I'm not sure if this is the problem, but certainly you should have this:
<button
onClick={() => deleteLead(lead.id)}
className="btn btn-danger btn-sm">
Delete
</button>
Your code as provided will call the deleteLead function as soon as the component is rendered!
deleteLead
is an action creator. Calling it with deleteLead(lead.id)
creates an action, which you then need to dispatch.
import { useDispatch } from 'react-redux'
const YourComponent = () => {
const dispatch = useDispatch() // or however else you want to get redux's dispatch function
return (
<button onClick={() => dispatch(deleteLead(lead.id))}>
Delete
</button>
)
}
To be able to use an action creator that returns a function instead of a plain action object, you will need to use the redux-thunk
middleware.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.