简体   繁体   中英

Array only has data inside event handler

I have a checkbox which calls my event handler

<Form.Check label='Januar 2019' id='jan19' onChange={handleCheck} />
<Form.Check label='Februar 2019' id='feb19' onChange={handleCheck} />

this is the handleCheck function

 function handleCheck (event) {
    // create the array with the valid months for 2019
    if (event.target.id === 'jan19' && event.target.checked) validMonths2019.push('01')
    if (event.target.id === 'feb19' && event.target.checked) validMonths2019.push('02')
}

And this the array

 const validMonths2019 = []

If console.log it inside the handleCheck function it is filled with data. But outside of the function is empty. How can I fix this? I need to send this array with a post request later on

useEffect(() => {

if(buttonValue === 'create') {
  // Reset the state of the stateful components
  setAlertValue(null)
  setLoading(true)
  setStatus(null)
  // here the array is emtpy..
  console.log(validMonths2019)
  axios
    .post('http://localhost:5000/', {
      contractId: contractId,
      contractCompletionQuote: contractCompletionQuote,
      iterations: iterations,
      validMonths2019: validMonths2019
    })

You need to store the validMonths2019 value in your component state.

Do this:

const ParentComponent = () => {
  const [validMonths2019, setValidMonths] = useState([])

  function handleCheck (event) {
    if (event.target.id === 'jan19' && event.target.checked) setValidMonths([...validMonths2019, '01'])
    if (event.target.id === 'feb19' && event.target.checked) setValidMonths([...validMonths2019, '02'])

    // Note: You might want to clean this up a bit to handle removing values from `validMonth2019` if the user un-checks the checkbox 
  }

  return (...)
}

What I would ultimately recommend though is that you make the checkbox components controlled, like this:

const ParentComponent = () => {
  const [validMonths2019, setValidMonths] = useState([])

  function handleCheck (val) {
    const newValidMonths = [...validMonths2019] // copies state so that it can be worked with before updating the state using the set method
    if (!validMonths2019.includes(val)) {
      newValidMonths.push(val)
      setValidMonths(newValidMonths)
    }
    else { // This is to remove it from state incase the user un-checks the checkbox
      newValidMonths.filter(v => v !== val)
      setValidMonths(newValidMonths)
    }
  }

  ...

  return (
    <>
      <Form.Check label='January 2019' id="jan19" checked={validMonths2019.includes('01')} onChange={() => handleCheck('01')} />
      <Form.Check label='February 2019' id='feb19' checked={validMonths2019.includes('02')} onChange={() => handleCheck('02)} />
    </>
  )
}

Try and set validMonths2019 as an array in the state using hooks:

const [ validMonths2019, setValidMonths2019 ] = useState([]);

Then you can do a handler so it does not reset every time you change it:

handleAddMonth = (newValue) => {
    const newArray = [ ...validMonths2019 ];
    newArray.push(newValue);
    setValidMonths2019(newArray);
}

That way you will have the data stored in the state and you'll be able to use it whenever you need it.

 var validMonths2019 = []; function handleCheck (event) { // create the array with the valid months for 2019 if (event.target.id === 'jan19' && event.target.checked) validMonths2019.push('01') if (event.target.id === 'feb19' && event.target.checked) validMonths2019.push('02') }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM