score:2
there's a few knots; i made this simplified sandbox (mocking an api call) of how it should work:
https://codesandbox.io/s/wonderful-minsky-99xi4?file=/src/app.js:0-799
index
import react from "react";
import reactdom from "react-dom";
import { createstore, applymiddleware } from "redux";
import { provider } from "react-redux";
import thunkmiddleware from "redux-thunk";
import rootreducer from "./rootreducer";
import app from "./app";
const store = createstore(rootreducer, applymiddleware(thunkmiddleware));
const rootelement = document.getelementbyid("root");
reactdom.render(
<provider store={store}>
<app />
</provider>,
rootelement
);
app
import react from "react";
import "./styles.css";
import { connect } from "react-redux";
import deleterequest from "./deleterequest";
const mapstatetoprops = state => {
return {
comments: state.comments
};
};
const mapdispatchtoprops = {
deleterequest: deleterequest
};
let app = ({ comments, deleterequest }) => {
const makedeleterequest = id => {
deleterequest(id);
};
return (
<div classname="app">
{comments.map(comment => {
return (
<div key={comment.id}>
<p>{comment.text}</p>
<button onclick={() => makedeleterequest(comment.id)}>
delete
</button>
</div>
);
})}
</div>
);
};
app = connect(
mapstatetoprops,
mapdispatchtoprops
)(app);
export default app;
reducer
const initialstate = {
data: [],
error: "",
comments: [{ id: 1, text: "test1" }, { id: 2, text: "test2" }],
loading: false,
editing: false
};
function rootreducer(state = initialstate, action) {
switch (action.type) {
case "delete_comment":
return {
...state,
comments: state.comments.filter(comment => comment.id !== action.id)
};
default:
return state;
}
}
export default rootreducer;
async action
import deletecomment from "./deletecomment";
const mockapi = new promise(function(resolve, reject) {
settimeout(() => resolve("deleted"), 2000);
});
const deleterequest = id => {
return dispatch => {
const makedeleterequest = async () => {
await mockapi;
dispatch(deletecomment(id));
};
makedeleterequest();
};
};
export default deleterequest;
delete comment action
export default function deletecomment(id) {
return { type: "delete_comment", id };
}
score:2
it looks like you're not actually dispatching the action, you're just returning an async action creator (deletecomment
function). in order your code to work, you need to first add redux-thunk
middleware to your redux store (so that you can use async action creators) and then, in your component, when you're calling deletecomponent
, you have to wrap the call using redux dispatch
.
if you're using a function component, you can add usedispatch
hook and have something like:
import {usedispatch} from "react-redux";
// ...
function mycomponent() {
const dispatch = usedispatch();
// ...
return <span classname="delete_info" onclick={() => dispatch(deletecomment(comment.id))}>delete</span>
}
or you can just use the connect
function to create a hoc and pass the dispatch
function from the provider's context:
const connectedcomponent = connect(undefined, dispatch => ({dispatch}))(mycomponent);
function mycomponent({dispatch}) {
return <span classname="delete_info" onclick={() => dispatch(deletecomment(comment.id))}>delete</span>;
}
Source: stackoverflow.com
Related Query
- Update single value in item array | react redux
- Material-UI Left Drawer in App Bar won't close on overlay click or menu item click in React
- React - Render Item inside map function by click event
- React Redux update item quantity (more than just one increment)
- react change the class of list item on click
- How to pass data by button click in redux react js
- how to handle click only one <li> item in react
- Add item in array with index - react redux and redux-saga
- How to set click listener on list item in material ui in react js
- Javascript / React - Remove specific item from Local Storage on click when rendered in another component
- Deleting an item from a collection in f, using React Redux
- Trigger Google Optimize experiment or any tag on click event in child or parent component, Application is build on Meteor React Redux
- Adding array item at specific index - React Redux
- React Redux - Issue removing an item
- React Redux deleting item from array at specific index
- React click on item to show details
- React Redux store not updating on delete of an item from state
- When click on item can't do this.setState REACT
- React router not rendering the component on click of a Array item
- How to delete item on click in React
- React redux - pushing new item to the state array not working
- get value of list item with click event in React
- How do I update a nested Item in a different reducer (slice) with redux toolkit in a React app
- Reference Item State Not Updated in React Redux on Save
- React Redux add line-through on checkbox click
- How to add item in redux with dictionary type in react typescript
- React Redux : update an item in an array of objects
- React - Dynamically appending click handlers in useEffect() + redux props
- React undefined item after redux delete
- React Redux Set Item Complete
More Query from same tag
- Use Vertical Steps component from antd with in a ScrollPanel from PrimeReact
- React Formik automatically giving me error whenever I write in a field
- Does material-ui useStyles really requires the entire props object?
- Two-Way Data Binding With Meteor and React
- Cannot correctly setup React-Router-Dom
- Place two arrows on each side of a div AND make it responsive
- How to get inner html with enzyme? (html content)
- Should I use react-loadable or loadable-components for code splitting?
- How to make multiple Axios requests using a dynamic array of links in Javascript?
- How to update redux state using a react variable passed up to the component from a child
- Why is Redux-Persist not persisting the store
- React cannot read property map of undefined
- How to implement each item without using for loop inside the useEffect?
- Converting nullable object values to strings in Typescript
- react router redux is not rendered on props changing
- How would one do two day data binding in React, having an input value A update when B is and vice versa, while keeping history of previous transforms?
- React render based on OR operator
- How do I hide the swiper pagination for specific slides in react?
- Cannot set multiple images
- Logic in component or mapStateToProps
- i have imported everything but still it throws this error TypeError: can't access property "url", postDetails is undefined
- React.forwardRef/Typescript defaultProps not working
- Set color on button click, like select unselect color change
- Update store based on user input data in React-Redux
- How can I get a mobile phone’s virtual keyboard height using javascript or css?
- How to iterate through keys of object with Yup
- Cookies not set when nodejs server is not on localhost
- TypeError: Cannot destructure property 'isLoading' of 'Object(...)(...)' as it is undefined
- Apollo React: How to refetch query when a different option is selected from select dropdown?
- Animation when I change a locale - framer motion