Home > Mobile >  Incrementing state in a parent from a child component in react
Incrementing state in a parent from a child component in react

Time:06-09

I have a component that has a counter in state, the child component does some checks and updates the count using an increment function that is passed to the child. I can see that it is working but it only ever increments to 1, what am I missing here

Parent Component

import { useState } from 'react'
import Child from './child'
function Parent() {
  const [count, setCount] = useState(0)
  const increment = () => {setCount(count  1)}
  const children = [
    {
      "name": "one",
      "answered": true,
      "id": "001"
    },
    {
      "name": "two",
      "answered": false,
      "id": "002"
    },
    {
      "name": "three",
      "answered": true,
      "id": "003"
    }
  ]
  return (
    <>
      <h1>Parent</h1>
      <progress id="file" max={children.length} value={count}>{count}/{children.length}</progress>
      <ul>
        {children.map((child, index) => {
          return (<Child key={index} increment={increment} child={child}></Child>)
        })}
      </ul>
    </>
  )
}
export default Parent

Child Component:

function Child(props) {
  const child = props.child
  if (child.answered) {
    props.increment()
  }
  return (<li>{child.name}</li>)
}
export default Child

CodePudding user response:

Firstly thank you @GalAbra

I fixed this by updating the setCount() to use a callback function. React's useState's setter will populate with the current value

const increment = () => {setCount(c => c  1)}

CodePudding user response:

Rather than using count and incrementing it every time doesn't seems to be optimized solution for this use case try this replace it with count

{children.filter(item => item.answered).length}
  • Related