React POST selected <li> item's ID - javascript

I want to get clicked <li> item's ID and POST this value with Fetch. I don't know how to handle with it. I'm waiting your help.
I explained my codes on this pic.
Basically i can list all users list inside <li> item. It works! But i need to get clicked item's "user.id" and save into a state like "setClickedUser". Then POST this ID with Fetch.
const [username, setUsername] = useState([]);
const [conversatid, setConversatId] = useState([]);
useEffect(()=>{
fetch('http://localhost:8000/api/current_user/', {
headers: {
Authorization: `JWT ${localStorage.getItem('token')}`
}
})
.then(res => res.json())
.then(json => {
setUsername(json.id);
});
},[])
const convcreate = (e, data, kullanici) => {
fetch('http://localhost:8000/api/conversat/', {
method: 'POST',
headers: {
Authorization: `JWT ${localStorage.getItem('token')}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({User1i: username, User2ii: clickeduser,})
})
.then(res => res.json())
.then(json => {
setConversatId(json.id);
}); };
const alluClicked = user => evt => {
/// GET CLICKED USER'S ID AND SAVE INTO "clickeduser"
}
return (
<div className="kullist">
{ props.allusers2 && props.allusers22.map( user => {
return (
<li key={user.id} onClick={alluClicked} className="tumtekkul">
<a> {user.username} </a>
</li> ); })} </div> ) }

You may do:
const alluClicked = userId => {
// SAVE userId where you need
}
return (
<div className="kullist">
{props.allusers2 && props.allusers22.map(user => {
return (
<li key={user.id} onClick={() => alluClicked(user.id)} className="tumtekkul">

I've solve that issue. I hope it will help another one.
const alluClicked = userId => {
fetch('http://localhost:8000/api/conversat/', {
method: 'POST',
headers: {
Authorization: `JWT ${localStorage.getItem('token')}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({User1i: username, User2ii: userId,})
})
.then(res => res.json())
.then(json => {
setConversatId(json.id);
});
}

Related

How to assign response from Api to an array using fetch function

I want to assign response in Fruits array ones I fetched the data from Api using fetch...But I am getting empty array when console.log.. I am getting the response from Api but not able to assign it to fruits
I am doing this way: .then(data => Fruits);
let Fruits = []
useEffect(() => {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + "eyJ0eXAiOiJKV1QiLCJhbGciOiJIwicm9sZSI6ImV4cGVydCJ9.6pYrAr_En0nl4N52oP1O7WRJA6PPFGCzUebauBIOEnc", },
body: JSON.stringify({"dfdfdffd"})
};
fetch('https://d.com/audis/el/lt', requestOptions)
.then(response => response.json())
.then(data => Fruits);
}, []);
Use a state
const [fruits, setFruits] = useState([]);
useEffect(() => {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + "eyJ0eXAiOiJKV1QiLCJhbGciOiJIwicm9sZSI6ImV4cGVydCJ9.6pYrAr_En0nl4N52oP1O7WRJA6PPFGCzUebauBIOEnc", },
body: JSON.stringify({"firebase_id":"foCzPM8MgOtg1"})
};
fetch('https://d.com/audis/el/lt', requestOptions)
.then(response => response.json())
.then(data => setFruits(data);
}, []);
You're not assigning data to anything. Try:
fetch('https://d.com/audis/el/lt', requestOptions)
.then(response => response.json())
.then(data => Fruits = data);
Also, you should use a state do store the information.
const [fruits, setFruits] = useState();
fetch('https://d.com/audis/el/lt', requestOptions)
.then(response => response.json())
.then(data => setFruits(data));
Maybe use a state?
const [fruits, setFruits] = useState([])
useEffect(() => {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + "eyJ0eXAiOiJKV1QiLCJhbGciOiJIwicm9sZSI6ImV4cGVydCJ9.6pYrAr_En0nl4N52oP1O7WRJA6PPFGCzUebauBIOEnc", },
body: JSON.stringify({"firebase_id":"foCzPM8MgOtg1"})
};
fetch('https://d.com/audis/el/lt', requestOptions)
.then(response => response.json())
.then(data => setFruits(data));
}, []);
console.log(fruits);

How to post a form with fetching?

I am trying to send a post with fetch an API.
My fetch is working because it returns 200 and sends the request but it sends an empty form.
It cannot take the values in the form input. Where is my mistake and how can I fix it?
...
const [contract, setContract] = useState("");
const form = useRef(null);
const submit = (e) => {
e.preventDefault();
const data = new FormData(form.current);
fetch(process.env.REACT_APP_ENDPOINT + "user/me/contract", {
method: "POST",
body: data,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${localStorage.getItem("fray_access_token")}`,
},
})
.then((res) => res.json())
.then((json) => setContract(json.contract));
};
return( ...
<form ref={form} onSubmit={submit}>
<Input
required
type="text"
value={contract.name}
onChange={(e) =>
setContract({ ...contract, name: e.target.value })
}
/>
<Input
required
type="text"
value={contract.surname}
onChange={(e) =>
setContract({ ...contract, surname: e.target.value })
}
/>
<Input
required
type="email"
value={contract.emai}
onChange={(e) =>
setContract({ ...contract, email: e.target.value })
}
/>
</form>
...)
[Update]:
You can either remove the application/json header and let browser post the form data implicitly using the multipart/form-data content-type :
const submit = (e) => {
e.preventDefault();
const data = new FormData(form.current);
fetch(process.env.REACT_APP_ENDPOINT + "user/me/contract", {
method: "POST",
body: data,
headers: {
Authorization: `Bearer ${localStorage.getItem("fray_access_token")}`,
},
})
.then((res) => res.json())
.then((json) => setContract(json.contract));
};
As #Quentin pointed out, we cannot serialise FormData using JSON.stringify so it's better to use explicit function to do it for you:
const serialize = (data) => {
let obj = {};
for (let [key, value] of data) {
if (obj[key] !== undefined) {
if (!Array.isArray(obj[key])) {
obj[key] = [obj[key]];
}
obj[key].push(value);
} else {
obj[key] = value;
}
}
return obj;
}
const submit = (e) => {
e.preventDefault();
const data = new FormData(form.current);
fetch(process.env.REACT_APP_ENDPOINT + "user/me/contract", {
method: "POST",
body: typeof data !== 'string' ? JSON.stringify(serialize(data)): data,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${localStorage.getItem("fray_access_token")}`,
},
})
.then((res) => res.json())
.then((json) => setContract(json.contract));
};
More details : https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Getting data from metaweather API to react page

I tried to use this metaweather API but it's not working. this is a react project and I'm tyring on localhost. plz, can anyone show me what am I doing wrong here?
const fetchWeatherData = async() =>{
fetch('https://www.metaweather.com/api/location/search/?lattlong=36.96,-122.02', {
method:'GET',
mode:'no-cors',
headers: {
'Content-Type': 'application/json',
},
})
.then(response => {
console.log('response',response);
return response.json();
})
.then(data => {
console.log('data',data);
})
.catch((err) => {
console.log(err)
})}
these are logs i got
You just didn't close the function with curly brackets, I have tested it and it works fine , just call the function fetchWeatherData
const fetchWeatherData = async() => {
fetch('https://www.metaweather.com/api/location/search/?lattlong=36.96,-122.02', {
method:'GET',
mode:'no-cors',
headers: {
'Content-Type': 'application/json',
},
})
.then(response => {
return response.json();
})
.then(data => {
console.log('data',data);
})
.catch((err) => {
console.log(err)
})
}
fetchWeatherData()

the code is doing its work but I'm not getting the desired output

whenever I click the delete button its works fine but I don't get the output like " deleted successfully " its shows .then undefined..
const deleteThisCategory = (CategoryId) => {
deleteCategory(CategoryId, user._id, token).then(data => {
if (data.error) {
console.log(data.error);
} else {
preload();
}
});
};
here is the delete category API call
export const deleteCategory = (userId, categoryId , token) => {
fetch(`${API}/category/${categoryId}/${userId}`, {
method: "DELETE",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type":"application/json"
},
})
.then(response => {
return response.json();
})
.catch(err => console.log(err));
};
It should be like this. deleteCategory needs to send only promise. Later where ever you are resolving you have to use then.
export const deleteCategory = (userId, categoryId , token) => {
return fetch(`${API}/category/${categoryId}/${userId}`, {
method: "DELETE",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type":"application/json"
}
})
};
const deleteThisCategory = (CategoryId) => {
deleteCategory(CategoryId, user._id, token).then(data => {
preload();
}).catch(err => {
console.log(err);
})
};

API Fetch update only one data

How can I update only one data through API? I want to change from status: 4 to status: 5
Here's my code
export const cancelRequest = async id => {
const response = await fetch(`API_URL/link/link/${id}`, {
method: 'put',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${Auth.getToken()}`,
},
});
return getData(response);
};
Calling it through another file
const onCancelRequest = async id => {
let cancelItem = dataAll.filter(item => item.id == id);
await TriggerRequestAPI.cancelRequest(id)
.then(data => {
data.json();
cancelItem[0].status = 5;
setIsAll(cancelItem);
})
.catch(error => console.log(error));
};
You need to update your item first then call the API:
const onCancelRequest = async id => {
const cancelItems = dataAll.filter(item => item.id == id);
if(cancelItems.length === 0) {
return;
}
// Update the item
cancelItems[0].status = 5;
// Then call the API
await TriggerRequestAPI.cancelRequest(id, cancelItems[0])
.then(data => {
return data.json();
})
.then(item => {
setIsAll(cancelItems);
})
.catch(error => console.log(error));
};
API:
export const cancelRequest = async(id, item) => {
const response = await fetch(`API_URL/link/link/${id}`, {
method: 'put',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${Auth.getToken()}`,
},
body: JSON.stringify(item) // item to update
});
return getData(response);
};

Categories

Resources