简体   繁体   中英

how can i set default value of array useState() react

I am getting an array of object list from backend API what my task is to set the first index of the value in a dropdown option to set it to default see an image I need to set that first user name in place of user

const [userL, setUserL] = useState([]);
  useEffect(() => {
    axios
      .get(`${DJANGO_SERVER_ADDRESS}/auth/analyst/`)
      .then((res) => {
        setUserL(res.data);
      })
      .then(
        (result) => {
        },
        (error) => {
        }
      );
  }, []);
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={user}
                name="user"
                onChange={handleSelectChangeL}
                placeholder="User"
                theme={(theme) => ({
                  ...theme,
                  colors: {
                    ...theme.colors,
                    text: "black",
                    primary25: "#d6fdf7",
                    primary: "#0bb7a7",
                    primary50: "#d6fdf7",
                  },
                })}
              ></Select>
            </Col>

see an image I need to set here that first user name

The parameter you pass in useState is the default value. You can pass a non-empty array:

const [userL, setUserL] = useState(['Default first value']);

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