Setting a jsx element value to fetch call value - reactjs

I'm making a custom jsx element. I want to set the element's value to data, that a fetch call returns:
const BoardPage = () => {
const id = useParams().id
fetch('http://localhost:8000/getBoardByID', {
headers: {
'Content-type': 'application/json'
},
method: 'POST',
body: JSON.stringify({ id: id })
}).then(response => response.json()).then(data => {
console.log(data)
return (
<div>
<h1>board #{data.id}</h1>
</div>
)
})
}
export default BoardPage
In console i see an object: {id: 31, board_content: '', width: 1223, height: 2323, user_privileges: '[]'}
But i get nothing as the output

You have to perform the request inside the useEffect hook.
const MyComponent = () => {
const id = useParams().id;
const [data, setData] = useState({});
React.useEffect(() => {
fetch("http://localhost:8000/getBoardByID", {
headers: {
"Content-type": "application/json",
},
method: "POST",
body: JSON.stringify({ id: id }),
})
.then((response) => response.json())
.then((data) => {
setData(data);
});
}, []);
return (
<div>
<h1>board #{data?.id}</h1>
</div>
);
};

Related

converting custom react function to async

I made this custom hook.
import axios from "axios";
import Cookies from "js-cookie";
import React from "react";
const useGetConferList= () => {
let token = JSON.parse(localStorage.getItem("AuthToken"));
const Idperson = JSON.parse(Cookies.get("user")).IdPerson;
const [response, setResponse] = React.useState();
const fetchConfer= (datePrensence, idInsurance, timePrensence) => {
axios({
method: "post",
url: `${process.env.REACT_APP_API_URL_API_GET_ERJASERVICE_LIST}`,
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
data: JSON.stringify({
datePrensence,
idInsurance,
Idperson,
searchfield: "",
timePrensence: parseInt(timePrensence) * 60,
}),
})
.then((r) => {
setResponse(r.data.Data);
})
.catch(() => alert("NetworkError"));
};
return { fetchConfer, response };
};
export default useGetConferList;
as you can see I export the fetchConfer function. but I want to make it async. for example, calling the function and then doing something else like this:
fetchConfer(Date, Time, Id).then((r) => {
if (search !== "") {
window.sessionStorage.setItem(
"searchList",
JSON.stringify(
r.data
)
);
}
});
as you can see in non async situation, I can't use then.
You can try this
const fetchConfer = async (datePrensence, idInsurance, timePrensence) => {
try {
const response = await axios({
method: "post",
url: `${process.env.REACT_APP_API_URL_API_GET_ERJASERVICE_LIST}`,
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
data: JSON.stringify({
datePrensence,
idInsurance,
Idperson,
searchfield: "",
timePrensence: parseInt(timePrensence) * 60,
}),
})
setResponse(response.data.Data);
// need to return data
return response.data.Data
} catch(error) {
alert("NetworkError")
}
};
use the function in another async function
const someAsyncFunc = async () => {
// try catch
const r = fetchConfer(Date, Time, Id)
if (search !== "") {
window.sessionStorage.setItem(
"searchList",
JSON.stringify(
r.data
)
);
}
...
or use it how you are currently using it
Hope it helps

How to set fetch data to text field in react-native function component

I am learning react-native and have a question about fetching data and passing them to a text component.
I fetched my data from my node.js back-end but don't know how to pass this data to component. Below is the code that i have tried so far.
const TableView = () => {
const [details, setDetails] = useState('');
const getUserData = async () => {
fetch('https://----.herokuapp.com/getIncomePerUser', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: data,
month: value,
}),
})
.then(response => response.json())
.then(response => {
console.log('Test');
console.log(response);
const array = response;
for (const i of array) {
const total = i.total;
setDetails(total);
console.log(total);
}
})
.catch(err => {
console.log(err);
});
});
};
useEffect(() => {
getUserData();
}, []);
return (
<Text Value={details}></Text> //I need to set my fetch data this text component
)
}
if you have an array of values and you want to show them you can use:
const TableView = () => {
const [details, setDetails] = useState('');
const getUserData = async () => {
fetch('https://----.herokuapp.com/getIncomePerUser', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: data,
month: value,
}),
})
.then(response => response.json())
.then(response => {
setDetails(response.map(r => r.total));
})
.catch(err => {
console.log(err);
});
});
};
useEffect(() => {
getUserData();
}, []);
return (<>
{details.map((d, i) => <Text key={i}>{d}</Text>)}
</>)
}
if you have a single value just replace your text component with:
<Text>{details}</Text>

How to show data using react

you are currently using react to replicate Spotify.
You are currently developing a search function and have successfully received a response.
I want to show this on the screen.
How do I solve this? Please help me.
const onClick = () => {
const inputSearchData = sessionStorage.getItem('inputData');
const inputTypeData = sessionStorage.getItem('inputType');
// console.log(inputTypeData)
axios({
headers: {
"Authorization": `Bearer ${token}`,
"Accept": "application/json",
"Content-Type": "application/json",
},
method: 'GET',
url: 'https://api.spotify.com/v1/search',
params: {
q: inputSearchData,
type: inputTypeData,
},
}).then((res) => {
console.log(res);
}).catch(err => {
console.log(err);
})
}
when you get your response from your axios request you need to store it inside react state.
access this inside the return statement of the component.
That will be something like that :
const SomeComponent = () => {
const [response, setResponse] = useState();
const onClick = async () => {
const inputSearchData = sessionStorage.getItem("inputData");
const inputTypeData = sessionStorage.getItem("inputType");
await axios({
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json",
"Content-Type": "application/json"
},
method: "GET",
url: "https://api.spotify.com/v1/search",
params: {
q: inputSearchData,
type: inputTypeData
}
})
.then((res) => {
setResponse(res);
})
.catch((err) => {
console.log(err);
});
};
return (
<div>
{/* Access your response state over here */}
{/* That will be something like that : */}
{response.map((item, index) => {
<div key={index}>
{item.somethingFromYourData}
</div>
})}
</div>
)
};

Update the likes array in a post in the frontend

I have a PUT route in the backend for liking posts, it adds the users id to the likes array in the post. This works fine when tested on Postman (by providing the post in the body) and the likes array is updated. However, when the icon is clicked in the frontend, I want the likes array to update but I'm not sure how to update the state for the post. result is showing the response in the frontend with a 200 status code but that's as far as I'm getting.
How can I update the likes array in the frontend?
Post.js
const Post = (props) => {
const [post, setPost] = useState({});
const [error, setError] = useState(false);
const id = props.match.params.id;
const loadSinglePost = (id) => {
read(id).then((data) => {
if (error) {
console.log(data.error);
setError(data.error);
} else {
setPost(data);
console.log(data);
}
});
};
useEffect(() => {
loadSinglePost(id);
}, [props]);
const like = (id) => {
const {user: { _id }, token} = isAuthenticated();
fetch(`${API}/like/${_id}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
id: id,
}),
})
.then(result => { console.log(result)})
.catch((err) => {
console.log(err);
});
};
return (
<div>
<Navbar />
<div>
<h3>{post && post.title}</h3>
<p>
{post && post.author ? post.author.name : ""}
</p>
<p>{post && post.body}</p>
<h5>{post && post.likes && post.likes.length} likes</h5>
<img
onClick={() => {
like(id);
}}
alt="..."
/>
</div>
</div>
);
};
export default Post;
controllers/post.js
exports.like = (req, res) => {
Post.findByIdAndUpdate(req.body._id, {
$push: {likes: req.profile._id}
}, {new: true}).exec((err, result) => {
if (err) {
return res.status(422).json({error: err})
} else {
return res.json(result)
}
})
}
exports.readById = (req, res) => {
const id = req.params.id
Post.findById(id)
.then(post => res.json(post))
.catch(err => res.status(400).json('Error: ' + err));
}
You can update likes in post in then callback like this:
const like = (id) => {
const {user: { _id }, token} = isAuthenticated();
fetch(`${API}/like/${_id}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
id: id,
}),
})
.then(result => {
// here update post likes
let updatedPost = {...post}; //to make copy of post
updatedPost.likes = [...updatedPost.likes, id]; //add new id to updatedPost' likes array
setPost(updatedPost); //update post
console.log(result)
})
.catch((err) => {
console.log(err);
});
};
Also from front-end you're sending id key in body:
body: JSON.stringify({
id: id, // here
})
And at back end you're expecting _id
Post.findByIdAndUpdate(req.body._id, { // here
$push: {likes: req.profile._id}
}

React Follow Function activates on page load

I am trying to implement a follow/unfollow function in a react rails-api web application. Currently the follow and unfollow post/delete just fine when I click the follow/unfollow button.
However, whenever a user visits another users page it will follow/unfollow when the page loads without clicking the follow/unfollow button. I do not understand why this is happening since I have, for my post/delete, the useEffect second param set to go off when the state for my follow/unfollow changes.
Please help me figure out why this is happening and how to prevent this. Let me know if more information is needed.
import React, {useState, useEffect} from 'react'
import {Link, useParams} from 'react-router-dom'
import decode from 'jwt-decode'
function NotUserPage() {
const {id} = useParams()
const [user, setUser] = useState({})
const loggedUser = decode(localStorage.getItem("token"))
const username = loggedUser.username
const userId = loggedUser.user_id
const [followUnFollow, setFollowUnFollow] = useState("true")
const toggleFollowUnFollow = () => {
setFollowUnFollow(!followUnFollow)
}
const fetchUserData = () => {
fetch(`http://localhost:3000/users/${id}`)
.then(res => res.json())
.then(data => setUser(data))
}
useEffect(() => {
fetchUserData()
}, [])
const unFollow = () => {
fetch(`http://localhost:3000/users/${id}/unfollow`, {
method: "POST",
body: JSON.stringify({
follower_id: userId,
followee_id: id
}),
headers: {
"Content-type": "application/json",
"Authorization": `bearer ${localStorage.getItem("token")}`,
},
})
.then(res => res.json())
.then(data => console.log(data))
}
useEffect(() => {
unFollow()
}, [followUnFollow])
const handleFollow = () => {
fetch(`http://localhost:3000/users/${id}/follow`, {
method: "POST",
body: JSON.stringify({
follower_id: userId,
followee_id: id
}),
headers: {
"Content-type": "application/json",
"Authorization": `bearer ${localStorage.getItem("token")}`,
},
})
.then(res => res.json())
.then(data => console.log(data))
}
useEffect(() => {
handleFollow()
}, [followUnFollow])
const fButton = () => {
toggleFollowUnFollow() ? handleFollow() : unFollow()
}
return (
<div>
{user.username}
<button onClick={fButton}>follow</button>
</div>
)
}
export default NotUserPage
import React, {useState, useEffect} from 'react'
import {Link, useParams} from 'react-router-dom'
import decode from 'jwt-decode'
function NotUserPage() {
const {id} = useParams()
const [user, setUser] = useState({})
const loggedUser = decode(localStorage.getItem("token"))
const username = loggedUser.username
const userId = loggedUser.user_id
const [following, setFollowing] = useState(false)
const fetchUserData = () => {
fetch(`http://localhost:3000/users/${id}`)
.then(res => res.json())
.then(data => setUser(data))
}
useEffect(() => {
fetchUserData()
}, [])
const unFollow = () => {
fetch(`http://localhost:3000/users/${id}/unfollow`, {
method: "POST",
body: JSON.stringify({
follower_id: userId,
followee_id: id
}),
headers: {
"Content-type": "application/json",
"Authorization": `bearer ${localStorage.getItem("token")}`,
},
})
.then(res => res.json())
.then(data => console.log(data))
.then(() => setFollowing(false))
}
const handleFollow = () => {
fetch(`http://localhost:3000/users/${id}/follow`, {
method: "POST",
body: JSON.stringify({
follower_id: userId,
followee_id: id
}),
headers: {
"Content-type": "application/json",
"Authorization": `bearer ${localStorage.getItem("token")}`,
},
})
.then(res => res.json())
.then(data => console.log(data))
.then(() => setFollowing(true))
}
const fButton = () => following ? unFollow() : handleFollow();
return (
<div>
{user.username}
<button onClick={fButton}>follow</button>
</div>
)
}
export default NotUserPage

Resources