简体   繁体   中英

I need to set default value of array of object reactjs

I am getting an array or an object from the backend what my task is to set the first index mean [0] to set in default value but when I set I am getting undefined you can see in code userL taking my array of an object but when I print userle it's showing label: undefined value: undefined or when I print userL I'm getting my array of object list

 const [userL, setUserL] = useState([]);
  useEffect(() => {
    axios
      .get(`${DJANGO_SERVER_ADDRESS}/auth/analyst/`)
      .then((res) => {
        setUserL(res.data);
      })
      .then(
        (result) => {
        },
        (error) => {
        }
      );
  }, []);
  console.log("ena1", userL);

const [userle, setUserle] = useState(
   { value: userL[0].username,
    label: userL[0].username,
  });
  console.log("nnnnnnnnnuuuu",userle)
console.log('nnnnnnnnnnn',userL[0])
const handleSelectChangeL = (object, action) => {
    setIndex(userL[object.id]);
    setUserlevel(null);
    console.log("select check", object.label, action.name, index);
    let name = action.name;
    let value = object.value;

    setFormData((prevFormData) => ({
      ...prevFormData,
      [name]: value,
    }));
  };
           <Col lg={2}>
              <label for="user">
                <header>User</header>
              </label>
              <Select
                options={userL.map((data, index) => ({
                  value: data.username,
                  label: data.username,
                  id: index,
                }))}
                styles={styles2}
                value={userle}
                name="user"
                onChange={handleSelectChangeL}
                placeholder="User"
                theme={(theme) => ({
                  ...theme,
                  colors: {
                    ...theme.colors,
                    text: "black",
                    primary25: "#d6fdf7",
                    primary: "#0bb7a7",
                    primary50: "#d6fdf7",
                  },
                })}
              ></Select>
            </Col>

If you want to set the state of the userle from the first element of the data, do it this way.

const [userle, setUserle] = useState()
const [userL, setUserL] = useState([]);
  useEffect(() => {
    axios
      .get(`${DJANGO_SERVER_ADDRESS}/auth/analyst/`)
      .then((res) => {
        setUserL(res.data);
        setUserle(res.data[0]?.username);
      })
      .then(
        (result) => {
        },
        (error) => {
        }
      );
  }, []);

EDIT

To also update the userle state onChange of the dropdown list, add setUserle() under your handleSelectChangeL function.

JS

const handleSelectChangeL = (object, action) => {
    setIndex(userL[object.id]);
    setUserlevel(null);
    console.log("select check", object.label, action.name, index);
    let name = action.name;
    let value = object.value;
    
    setUserle(value); // Add this line   

    setFormData((prevFormData) => ({
      ...prevFormData,
      [name]: value,
    }));
  };

if you using useState, You cannot get expected result of updated state in same function, but if want to print the result, you must write useEffect with dependency userle state or maybel you can console it above "return" statement in functional Commponent

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