1

This is what I'm trying to do inside the export default function

   const Create = () => {
  handleClose();
  let temp = '';
  if (thing1) {
    temp= 'text';
  }
  if (thing2) {
    temp += 'text';
  }
  if (thing3) {
    temp += 'text';
  }
  if (thing4) {
    temp += 'text';
  }
  if (thing5) {
    temp += 'text';
  }
  setsel(temp);

Obviously I have something else for temp, having it loop through things to get a value but that's the basic idea - It comes back as undefined when I console.log "thing" to test it out.

Filotimo
  • 56
  • 5

3 Answers3

1

Utilising the answer from stackoverflow.com/a/67681192/10004072 to suit your context

import React, { useState, useEffect } from "react"

const [thing, setthing] = useState(''); // the state on update of which we want to call some function

const someAction = () => {
  let temp = 'test';
  setthing(temp); // the state will now be 'test'
}

useEffect(() => { // this hook will get called every time when thing has changed
   console.log('Updated State', thing)
}, [thing])
Leslie Alldridge
  • 1,427
  • 1
  • 10
  • 26
0

Your question is incomplete and lacks information. What exactly do you want to do?

If you want to set a value to the initial thing state, put inside the use state what you want to put. Example:

const [thing, setthing] = useState(test);

why do you want to set the value of another variable to the thing state? why not set it directly?

duck_go19
  • 49
  • 6
  • As I mentioned but I probs wasn't specific, it doesn't show the full thing - Basically, I have conditionals for the temp, which happens after all the const declarations for useState and others (there are many others) - Thus, I need to set it after – Filotimo Aug 01 '22 at 02:29
  • I added more context – Filotimo Aug 01 '22 at 03:13
0

Leslie's answer looks correct to me

Here is what's going wrong with example you shared:

Referring to the documentation: https://reactjs.org/docs/hooks-reference.html#usestate

The setState function is used to update the state. It accepts a new state value and enqueues a re-render of the component.

setthing(temp) is not going to change value of thing in this render, it is going to render with current value, and then re-render the component with thing set to temp. Which in the sample example you shared will result in infinite renders.

Amit Khanna
  • 489
  • 4
  • 16