duplicate entry while using push on array - reactjs

The collaborators contain 3 data already and I am trying to push a user which should come first. I am baffled while I tried to use console.log(), I am getting 3 response values instead one. As illustrated below; it referenced to the line 25 and it printed trice.
However, when I pushed to collaborator, I am expecting a value but I got two data values pushed to collaborator. I just want one. I have spent several hours trying to figure what I have done wrongly. Please, I don't know how, that is why I posted here.
const resData = async() => {
const res = await directus.users.me.read()
const result = res.data
console.log(result)
collaborators.push(result)
}
resData()

I finally solved it by using useEffect.
useEffect(() => {
const resData = async() => {
const res = await directus.users.me.read()
const result = await res.data
collaborators.unshift(result)
}
resData()
},[collaborators])

Related

How can I access 2 data attribute value using useRef hook?

here I am confused about accessing 2 parameters on the endpoint.
/api/nad/buildingCount/:provinsi/:kota
Previously I was able to access 1 parameter using useRef, for example like this =
const provinsi = provinsiRef.current[index].dataset.value;
But when I tried for the 2 parameters, it was beyond my expectations.
This is my code, is there something wrong?. please for the solution, thank you
const handleKota = async (index) => {
try {
const provinsi = provinsiRef.current.dataset.value;
const kota = provinsiRef.current[index].dataset.value;
setIsLoading(true);
const result = await getBuildingOLDallKecamatan(provinsi, kota);
setDataKecamatan(result);
console.log(result);
} catch (error) {
} finally {
setIsLoading(false);
}
};
It seems that when you call handleKota, only one index is passed to the function, but the index in provinsiRef.current[index] and in kotaRef.current[index] are different, since these are 2 different ref array.
From your links to full code:
const handleKota = async (index) => {
try {
const provinsi = provinsiRef.current[index].dataset.value;
const kota = kotaRef.current[index].dataset.value;
setIsLoading(true);
const result = await getBuildingOLDallKecamatan(provinsi, kota);
setDataKecamatan(result);
console.log(result);
} catch (error) {
} finally {
setIsLoading(false);
}
};
As a result you might be getting mismatched provinsi and kota.
Possible solutions
Data attribute can carry a number of values. Therefore, you can give each kota item a value of provinsi they belong, such as data-provinsi. This way, you just need to access the kota ref, not both, to get everything needed for handleKota.
Instead of using ref to access data-set, use an approach that is not dependent on index. This does require some major refactor of existing code though. Perhaps check this answer for a quick example about accessing data-set with the event object.

Firebase, trying to pull the collection based on a ID?

Basically, I have two collections per post. One with the comments on the post and one with the post information. The formula I wrote gives me the data of the post information. I want it to return both collections so I can map through the comment collection. but I cannot seem to figure out how to get it to send me to one level up basically. Any help would be appreicated!
const docRef = doc(db, "posts", postId);
useEffect(() => {
if(postId){
const getUsers = async () => {
const data = await getDoc(docRef)
console.log(data.data())
}
getUsers()
}
}, [])
The answer I was looking for is as follows!
const stepOne = collection(db,"posts")
const stepTwo = doc(stepOne,postId)
const stepThree = collection(stepTwo,"comments")
const stepFour = onSnapshot(stepThree,((snapshot)=>snapshot.docs.map((doc)=>console.log(doc.data()))))
Through this structure on the picture, comments are a collection nested inside posts, right? If so, then you cannot return a subcollection from a simple query on the parent document. Try fetching the post info first, then fetch the comments from an other query
this is for posts:
const docRef = doc(db, "posts", postId);
the path for comment will be
"posts/postId/comment"

How to set data to the state after fetching from backend?

I want to get data from the backend and want to set those data to the state in ReactJS. Here is my source code
const [eachAsset, setEachAsset] = useState([]);
function ShowModalView(id)
{
axios.get("http://localhost:8070/assets/detail/"+id).then((res)=>{
const data = res.data
setEachAsset(data)
//console.log(eachAsset);
}).catch((err)=>{
console.log(err.message);
})
setShow2(true);
}
When I uncomment the console log, it shows an empty array. It means, setEachAsset(data) does not work properly. But I want to store data that are getting from the backend to the eachAsset state. What is the problem of this source code?
setEachAsset([...data])
I hope this would work
I would recommend using async-await which makes the code easier to read and understand the flow of the program as compared to promise chains.
const [eachAsset, setEachAsset] = useState([]);
const ShowModalView = async (id) => {
try {
const resp = await axios.get("http://localhost:8070/assets/detail/"+id);
setEachAsset(resp.data)
console.log(resp.data);
} catch (err) {
// Handle Error Here
console.error(err);
}
setShow2(true);
}

How I can display only one object from API array Reactjs

How I can display only one object from [data.hits]? Ive tried map(), filter, also setRecipes([data.hits.recipe[0]]); etc ... and it doesn't work. Currently, it shows 10 objects on the website but I need only one. Thank you for any help.
const [recipes,setRecipes] = useState ([]);
useEffect(()=>{
getReciepes();
},[query]);
const getReciepes = async () => {
const response = await fetch (`https://api.edamam.com/search?
q=${query}&app_id=${APP_ID}&app_key=${APP_KEY}`);
const data = await response.json();
setRecipes(data.hits);
console.log(data.hits);}
I dont know how I did not notice this. Here is a simple solution :
const list=[...data.hits]
list.length = 1
setRecipes(list);
console.log(list);
}

after axios get my setState hooks doesn't run

I have a lot of functions like this, using the same approach, and they all run fine.
But this one is going me crazy.
My code is:
const [match,setMatch] = useState(null);
axios.get(path)
.then((res) => {
status = res.data;
setMatch(res.data)});
const test = match;
If I debug the program and break at setMatch(status), the content of res.data is correct:
res.data is an array, and each element contains a mix of values and objects as show in the screenshot below.
But when I execute the setMatch(status) the result is that the match state variable doesn't change: it remains null as set the first time.
Can someone provide some suggestion?
From your question, I dont know what could likely affect your code from running. But this is the common pattern when handling asynchronous request.
It is expected that it should be executed in the useEffect hook right after it is painted
const Component = () => {
const [match,setMatch] = useState([]);
useEffect(() => {
axios.get(path)
.then((res) => {
status = res.data;
setMatch([match, ...res.data])})
.catch((err) => handleError(err));
}, [path]) // assuming that the path changes otherwise if you are running this once, leave the array empty
return (<div> {(match.length > 0)? 'Loading': {renderYourLogicHere} </div>)
}

Resources