简体   繁体   中英

How to change react state with spread operator

I need help regarding changing the state of array of objects when fetching data.

This is my use state.

  const [productData, setProductData] = useState<[{label: string, value: string}]>([{
    label: '',
    value: '',
}]);

And this is the function where i make api call and will change my state taking from array of objects the name of the products, so data.name. I am trying to map all the names so that i can show in a dropdown.

  const getAllProducts = async () => {
    try {
      const { data } = await axios.get(`http://localhost:8300/product/all`);
      data.map((product: any) => setProductData());
    } catch(error) {
      console.log("Error", error);
    }
  };

How would i be able to do this in react typescript. Change the label and value field with the mapped values so that i can show in the dropdown.

type ProductData = {
  label: string;
  value: string;
};

const [productData, setProductData] = useState<ProductData[]>([
  {
    label: '',
    value: '',
  },
]);
const updateProductData = (newProductData: ProductData[]): void => {
  setProductData((currentState) => {
    const draft = newProductData;

    // mutate your draft however you'd like...

    return [...currentState, ...draft ];
  });
  return;
};
const getAllProducts = async (): ProductData[] => {
  const newProductData = await // ...
  updateProductData(newProductData);
  return;
};

Check the 2nd Note in useState docs

You might find useReducer more useful though.

You are already making an API call and getting the response here.

const getAllProducts = async () => {
  try {
    const { data } = await axios.get(`http://localhost:8300/product/all`);
    data.map((product: any) => setProductData()); <-- prepare your object here
  } catch (error) {
    console.log("Error", error);
  }
};

Once you get the response, prepare the objects that are required for your dropdown. Something like below.

const dropdownValues = data.map((product: any) => ({ id: product.id, label: product.name, value: product.id }));
setProductData(dropdownValues);

Use the ProductData in your dropdown tag.

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