score:1
in the second reducer, you're getting the data from the cats
import, instead of from the state! so your reduce is always returning an object from the import instead of from whatever state is passed in. you should not be importing cats
in your reducer code.
similarly in your first reducer, you are returning data from the cats import.
in both cases, you should be returning data from the state
parameter passed in, not from the cats
import.
your first reducer would then look like this:
export default (state = cats, action) => {
switch(action.type) {
case 'increment':
return state.map(cat => cat.name === action.name ? {...cat, clickcount: cat.clickcount + 1} : {...cat});
default:
return state;
}
}
second reducer:
export default (state = cats[0], action) => {
switch(action.type) {
case 'set_current_cat':
return {...state.filter(cat => cat.name === action.name)[0]};
default:
return state;
}
}
note that the reducer body code references state
, not cats
.
also note that the reducers now return new objects that are clones of the objects in state (not the original objects), using the object spread operator: {...cat}
and {...state.filter()[0]}
.
it's not necessarily a problem to import cats
and use it as the default, though it's not the best design. (the problem is that the code isn't using the state parameter at all, and is instead using the imported object collection.) to avoid using the cats import in the reducers entirely, one option is to pass them in as the default store contents to createstore
:
import cats from '../cats';
const defaultstate = { cats, currentcatname: 'lucy' };
const store = createstore(
rootreducer,
defaultstate
);
then the defaults for the reducer parameters should return an empty array for the first reducer:
export default (state = [], action) => {
and an empty object for the second reducer:
export default (state = {}, action) => {
another alternative is to add a load_cats
action that populates your cat collection, perhaps dispatched on componentdidmount for your top level app component.
another optimization that will help avoid using existing objects is to change set_current_cat to simply change the cat name/id stored in the state:
export default (state, action) => {
switch(action.type) {
case 'set_current_cat':
return action.name;
then to get the current cat, you can add a selector that gets the cat by name/id from the state returned by the first reducer. (adding an id field helps you handle the scenario where there are multiple cats with the same name.) the selector might look like this:
function getcatbyname(state, name) { return state.cats.filter(cat => cat.name === name) }
score:1
you're mutating state when you use the ++ operator on it. use a simple addition instead
return cats.map(cat => cat.name === action.name ? {...cat, clickcount: cat.clickcount + 1} : cat);
Source: stackoverflow.com
Related Query
- Why the original data is mutated in this simple task?
- Why this sort function is not returning to the original order?
- Why would this say TypeError: users.map is not a function when my logs say the data in question is an array?
- Why when using React useState is the payload data clearing on a onsubmit event? This is a POST request to the server side
- Dirt simple reactjs program - why is the data not displaying?
- why does this error occur during fetch data from the backend
- Uncaught Error: Invariant Violation: findComponentRoot(..., ...$110): Unable to find element. This probably means the DOM was unexpectedly mutated
- Suddenly React cannot execute the 'create-react-app' command. Why is this happening and how can I solve it?
- Why doesn't this select list render with the correct item selected based on the defaultValue
- Why is this returning the error .contains() is not a function
- Why isn't Form.Select recognized in my simple react-bootstrap app, following the react-bootstrap documentation?
- Why is clearTimeout not clearing the timeout in this react component?
- ReactJS + Redux: Why isn't MongoDB saving data to the database even with correct API requests?
- Why is this variable from the Redux store not in the `this.props` on React page?
- Why the original source code is showing in the source using webpack? And how to disable it?
- React child callback binding this without overriding the original this
- How would I scrape the JS-generated data on this webpage?
- Why does this React component return the string '0'
- Why is the state not updating inside this react Hooks component?
- What is the difference between passing data in this way to properties in React?
- Why doesn't react-sticky work in this simple example?
- Why the data not displayed in nextjs?
- useState() in react does not update the data - is this the sort() issue?
- Why is there a semi-colon in the object structure for expected props in this typescript react component?
- Why is my data that is coming from apollo server not showing up when I refresh the page?
- Why does data from my api only display once and when I refresh the page it gives an error
- Why state doesn't keep all the data in Array state in hook when it updated in foreach?
- Why do I see the warning about using act when testing this hook?
- Why is this app code only working from the right side or else the ReactDOM.findDOMNode querySelector cant find className
- Why does the useEffect() seem to reset my local state after receiving data from a socket?
More Query from same tag
- Reducer Typescript Error: No overload matches this call
- How does React router works and what is the difference between <link> and<Route>
- How can I get the Marker being dragged when event handler is already bound?
- Getting data from another class to main screen in react js and redux
- How to add title of a article into URL in Reactjs?
- this.setState is not a function error is persistent even though I have followed many examples that use the same code
- React-Router 1.0.0 Uncaught Error: Invariant Violation: Element type is invalid
- Added todo-object in array(state) is not reversed immidiately
- Render table columns that will fill full width.
- How can I convert bbcode characters to jsx? (enriching text)
- How to put an error message when putting the credentials wrong in a login
- How to deploy a React + NodeJS Express application to AWS?
- Fetch data from API and redirect not working - NEXTJS
- Make useEffect only run when component is in view (i.e. scrolled down to that component)
- Component don't re render after state update
- NextJS: Pass string via context from input into getStaticProps
- Sending FormData from modal to parent component's method in react
- Testing React component with data provided by custom hook
- activeClassName for links with similar urls
- After button is clicked , Unable to reset the data
- what happens to http request when route changes in SPA
- Define type of the component
- React js material ui core table get data from row on click
- Enzyme - Test if a nested component is correctly rendered
- How to added text to specific mapped element?
- Problem with react-hook-form - api gets null values
- React and i18n - translate by adding the locale in the URL
- Dynamically wrap a js string by span tags which can be dangerously rendered in React
- How to render react component determined by string in TSX
- how to get axios to return the object instead of promise