1

Home.js

import React, { useState, useEffect } from 'react'
import './HomeCss.css'
import { Card, Button, Container, Row, } from 'react-bootstrap'
import Axios from 'axios'
import { useStoreActions, useStoreState } from 'easy-peasy'

const Layout = () => {
  const [items, setItmes] = useState([])
  const count = useStoreState(state => state.count)
  const add = useStoreActions(actions => actions.add)

  useEffect(() => {
    Axios.get('http://localhost:3000/products')
      .then(res => {
        setItmes(res.data)
      })
      .catch(err => {
        console.log(err)
      })
  })


  function displayCard() {
    if (!items.length) return null

    return items.map((item, index) => (
      <Card style={{
        width: '21rem',
        marginRight: "7px",
        marginLeft: '7px',
        marginBottom: '13px',
        display: 'flex',
        alignItems: 'center'
      }}>
        <Card.Img variant="top" src={item.url} />
        <Card.Body>
          <Card.Title>{item.title}</Card.Title>
          <Card.Text>
            {item.description}
          </Card.Text>
          <Button variant="primary"
            onClick={() => add()}
          >
            Buy Now
              </Button>
        </Card.Body>
      </Card>
    ))
  }

  console.log(count)

  return (
    <div>
      <Container><Row>{displayCard()}</Row></Container>
    </div>
  )
}

export default Layout

Due to onClick={() => add()} line on the above code i am having this error: Error: First argument to createDraft must be a plain object, an array, or an immerable object

And this is how model.js file look’s like from where i am getting this state.count and actions.add inside my Home.js file above if somehow it’s usefull:

model.js

import { action } from "easy-peasy";

export default {
    count: 0,
    add: action((state, id) => {
        return state.count + 1
    })
};

Here is the link to repo:https://github.com/charanpreet-byte/Commerce-website/blob/master/client/src/pages/Home.js

1 Answers1

0

model.js

import { action } from "easy-peasy";

export default {
    count: 0,
    add: action((state, id) => {
        state.count += 1
    })
};

Error is coming from Immer. Immer lets you use an imperative API and should be modifying the value like this state.count += 1, not returning a new one like this return state.count + 1 inside the model.js file above.

  • Code-only answers are discouraged on Stack Overflow because they don't explain how it solves the problem. Please edit your answer to explain what this code does and how it answers the question, so that it is useful to other users with similar issues. – FluffyKitten Sep 28 '20 at 05:32