How to update final object using callback data - javascript

I have an object with keys id,name like below. Based on the id i have to get customer name and update the object.
Const arr=[{id:1,name:''},{id:2,name:''}];
_.forEach (arr, function (obj)){
const result=getcustomer(obj.id, function (data){
//Getting customer data here.
});
}
How can i update obj.name for each object when i get data asynchronously?

Would you not just get the index of the item you are currently on and update that array element? Or am I missing something here.
arr.forEach((item, index) => {
const result = await getCustomer(item.id);
arr[index].name = result.data.name; //however you get the data
});

Related

how can i get a object from json in react?

i have to get some data from a complex objects json (in my case is: valor_custo_fornecedor from the detalhe object, how can i do this ?
i already tried with axios like this:
const [valorCusto, setValorCusto] = useState([]);
useEffect(() => {
axios.get('MY API LINK').then((res) => {
let valor = res.detalhe.valor_custo_fornecedor;
setValorCusto(res.valorCusto.valor_custo_fornecedor);
});
});
It is hard to tell without seeing the complete json what key/value pairs exist in the data, but from what I can see you are passing a value that does not seem to exist in the data to setValorCusto, namely: res.valorCusto.valor_custo_fornecedor
I am guessing what you want to pass to setValorCusto is the valor variable that you have defined above? However the res.data.detalheis as others have replied an array, which you would either have to iterate through or specify an index for.
Another detail, not relating to the question in itself, is that I would add a dependency array to the effect, so that this api request is not called on every component re-render. So the end result would look something like this:
const [valorCusto, setValorCusto] = useState([]);
useEffect(() => {
axios.get('MY API LINK').then((res) => {
const valor = res.data.detalhe.map((detalheItem) => {
return detalheItem.valor_custo_fornecedor;
});
setValorCusto(valor);
});
}, []);
Notice the empty array as the second parameter in the useEffect call. This means that the effect will only be run on the initial rendering of the component.
Then you can access the value by simply using valorCusto wherever you need it in the component.
After setting response in setValorCusto ; you can loop over you state variable and get the desired value
Like the other answers state. What you are returning from your API is an array of objects. Currently in your code, that array lives inside the response object. So in this snippet below:
axios.get('MY API LINK').then((res) => {
let valor = res.detalhe.valor_custo_fornecedor;
You need to specify from which item in the array you would like to get the detalhe object from (like res[0].detalhe).
One way you could do if you like to use everything from the array, is to store the entire array in your useState. Afterwards, you could loop over the array and do something with the objects inside of it.
PS. If you're not entirely sure what the state holds. You could log it to the page by doing something like <div>{JSON.stringify(valorCusto)}</div>
export default function App() {
const [valorCusto, setValorCusto] = useState(null);
useEffect(() => {
const getData = async () => {
const res = await axios.get("API");
const data = await res.data;
setValorCusto(data);
};
getData();
}, []);
return (
<main>
<div>
{valorCusto.map((item) => {
<div>{item.id}</div>;
})}
</div>
</main>
);
}
You can convert json like this:
useEffect(() => {
axios.get('MY API LINK').then((res) => {
let obj = JSON.parse(res.detalhe.valor_custo_fornecedor)
});
});

Filter Array of objects (API response) based on flag in database

I am receiving a large array of objects using the below method:
const GetList = async () => {
const [data, error] = await GetList();
console.log(response);
This gives me back an array of 1000 elements, there is an isActive flag on every element and I need to filter out the elements that are not active.
I am not able to use
var resultFiltered = response.filter(obj =>{
return obj.isActive === 'true'
});
As it gives me an error message
The entire array is stored in the data variable, how can I filter out all elements that are not active?
I'm not sure why you are using response variable, since the value is fetched variable data, try filtering as shown below
const GetList = async () => {
const data = await GetList();
const resultFiltered = data.filter(obj => Boolean(obj.isActive) === true);
console.log(resultFiltered);
}
According to the error, the response variable is not an array-type variable please check that out. If it's an object then convert it into an array and then apply the filter function.
const resultFiltered = Object.values(response).filter(obj => obj.isActive === true);
Test the bellow code:
response.data.filter()

Deep copy of the Object to add a key : value

I am pre-fetching a product from a database using mongoose with next.js and react-query. I was wondering why I need to do a deep copy of a nested object in order to add a key:value to it. Otherwise it does not work. Let me know what I am not understanding.
await queryClient.prefetchQuery(['productSlug', slug], async () => {
const product = await read(slug);
const existingRatingObject = product.ratings.find(
(item) => item.postedBy.toString() === user._id.toString()
);
const copyProduct = JSON.parse(JSON.stringify(product));
if (existingRatingObject) {
copyProduct.star = existingRatingObject.star;
} else {
copyProduct.star = 0;
}
console.log({ copyProduct });
return JSON.stringify(copyProduct);
});
The reason is that the product fetched is a Mongoose document not a plain old JavaScript object.
When you convert it to plain old javascript Object, you will be able to add any key to it.
You can add .lean() to you query or add toObject/toJSON to you the fetched document

Unable to update array state on delete [React.js]

I am working on a React.js app where I have a functional component which contains state array, which I declared like this const [myArray, setMyArray] = useState([]).
I fetch some data from an API and add it to the array with no problem. But I am unable to delete an element of the array. First I delete it through the API and then I try to update the array, but it seems to not work.
Here is the code sample:
const deleteElement = (id) => {
fetch(URL,{method: "DELETE"}).then((response) => response.json()).then(deleteFromArray(id))};
const deleteFromArray = (id) => {
const filtered = myArray.filter((item) => item.id !== id);
setMyArray(filtered)
}
The filtered array is ok, it does not contain the deleted element. But I just can't figure out why the myArray does not get updated here.
I am new to React so any hints would be appreciated. Thanks
The setMyArray runs asynchronously so if you wrote like below, the result is always the old value but the array updated successfully.
const deleteFromArray = (id) => {
const filtered = myArray.filter((item) => item.id !== id);
setMyArray(filtered)
console.log(myArray); // old value
}
To see the updated array, you should use useEffect like below:
useEffect(() => { console.log(myArray) }, [myArray]);
This hook will runs everytime the myArray changed.

Firebase - How to get list of objects without using AngularFire

Firebase - How to get list of objects without using AngularFire
I'm using typescript, angular2 and firebase.
I'm not using angularfire. I want to extract the data using their Api
My firebase url is /profiles
This is the list of profiles I'm looking to extract:
Thanks.
Use a simple value event and re-assign the array every time the value changes.
JSBin Demo.
var ref = new Firebase('https://so-demo.firebaseio-demo.com/items');
ref.on('value', (snap) => {
// snap.val() comes back as an object with keys
// these keys need to be come "private" properties
let data = snap.val();
let dataWithKeys = Object.keys(data).map((key) => {
var obj = data[key];
obj._key = key;
return obj;
});
console.log(dataWithKeys); // This is a synchronized array
});

Categories