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.
CodePudding user response:
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.
CodePudding user response:
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.