I've been creating an app with NextJS, my problem came when I tried to generate new content from an API when I click on a button. I get the server call succesfully but it gets updated only when I reload the page, not when I click on the button as I want.
Here's the code:
import React, {useState} from 'react'
import { FaCog } from 'react-icons/fa'
export async function getServerSideProps() {
const res = await fetch(`https://animechan.vercel.app/api/random`)
const data = await res.json()
return {
props: {
quote: data.quote,
anime: data.anime,
character: data.character
}
}
}
const Button = () => {
const [clicked, setClicked] = useState(false)
const handleClicked = (props) => {
return (
<div>
<p style={{fontWeight: 'bold'}}>{props.anime}</p>
<p>{props.quote}</p>
<p style={{fontWeight: 'bold'}}>-{props.character}</p>
</div>
)
setClicked(!clicked)
}
return (
<div className="main_button">
<button onClick={handleClicked}>{clicked ? 'Generate again...' : 'Generate content '} <FaCog className={clicked ? 'main_button-spinner' : null}/> </button>
</div>
)
}
export default Button
I want that each time I click on the button, the content gets updated and I receive new content from the API. As I explained above, this is working fine on the API call, but the content gets updated just by reloading the page and not as I need it to work. Any idea?
You're misunderstanding the role of getServerSideProps. Take a look at the Next.js documentation: https://nextjs.org/docs/basic-features/data-fetching/get-server-side-props
getServerSideProps only runs on server-side and never runs on the browser
If you want your React application to change in response to hitting this API, then you need to submit a request to the API from within the React code (in response to the button click), save the results of the API to state, and then display the results in the frontend.
Psuedo code follows:
const [data, setData] = useState(null);
// ...
async function handleClicked() {
const apiResponse = await fetch("...");
setData(apiResponse); // Or whatever properties from the response you care about
}
// ...
<button onClick={handleClicked}>
{clicked ? 'Generate again...' : 'Generate content '}
<FaCog className={clicked ? 'main_button-spinner' : null}/>
</button>
Related
I'm trying to send a delete request to delete an item from an API.
The API request is fine when clicking on the button. But Item get's deleted only after refreshing the browser!
I'm not too sure if I should add any parameter to SetHamsterDeleted for it to work?
This is what my code looks like.
import React, {useState} from "react";
const Hamster = (props) => {
const [hamsterDeleted, setHamsterDeleted] = useState("")
async function deleteHamster(id) {
const response = await fetch(`/hamsters/${id}`, { method: "DELETE" });
setHamsterDeleted()
}
return (
<div>
<p className={props.hamster ? "" : "hide"}>
{hamsterDeleted}
</p>
<button onClick={() => deleteHamster(props.hamster.id)}>Delete</button>
<h2>{props.hamster.name}</h2>
<p>Ålder:{props.hamster.age}</p>
<p>Favorit mat:{props.hamster.favFood}</p>
<p>Matcher:{props.hamster.games}</p>
<img src={'./img/' + props.hamster.imgName} alt="hamster"/>
</div>
)
};
export default Hamster;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Imagine you have a parent component (say HamstersList) that returns/renders list of these Hamster components - it would be preferable to declare that deleteHamster method in it, so it could either: a) pass some prop like hidden into every Hamster or b) refetch list of all Hamsters from the API after one got "deleted" c) remove "deleted" hamster from an array that was stored locally in that parent List component.
But since you are trying to archive this inside of Hamster itself, few changes might help you:
change state line to const [hamsterDeleted, setHamsterDeleted] = useState(false)
call setHamsterDeleted(true) inside of deleteHamster method after awaited fetch.
a small tweak of "conditional rendering" inside of return, to actually render nothing when current Hamster has hamsterDeleted set to true:
return hamsterDeleted ? null : (<div>*all your hamster's content here*</div>)
What do you want to do in the case the hamster is deleted? If you don't want to return anything, you can just return null.
I'm not too sure if I should add any parameter to SetHamsterDeleted for it to work?
Yes, I'd make this a boolean instead. Here's an example:
import React, { useState } from "react";
const Hamster = (props) => {
const [hamsterDeleted, setHamsterDeleted] = useState(false);
async function deleteHamster(id) {
const response = await fetch(`/hamsters/${id}`, { method: "DELETE" });
setHamsterDeleted(true);
}
if (hamsterDeleted) return null;
return (
<div>
<p className={props.hamster ? "" : "hide"}>
{hamsterDeleted}
</p>
<button onClick={() => deleteHamster(props.hamster.id)}>Delete</button>
<h2>{props.hamster.name}</h2>
<p>Ålder:{props.hamster.age}</p>
<p>Favorit mat:{props.hamster.favFood}</p>
<p>Matcher:{props.hamster.games}</p>
<img src={'./img/' + props.hamster.imgName} alt="hamster"/>
</div>
);
};
HOWEVER! Having each individual hamster keep track of its deleted state doesn't sound right (of course I don't know all your requirements but it seems odd). I'm guessing that you've got a parent component which is fetching all the hamsters - that would be a better place to keep track of what has been deleted, and what hasn't. That way, if the hamster is deleted, you could just not render that hamster. Something more like this:
const Hamsters = () => {
const [hamsers, setHamsters] = useState([]);
// Load the hamsters when the component loads
useEffect(() => {
const loadHamsters = async () => {
const { data } = await fetch(`/hamsters`, { method: "GET" });
setHamsters(data);
}
loadHamsters();
}, []);
// Shared handler to delete a hamster
const handleDelete = async (id) => {
await fetch(`/hamsters/${id}`, { method: "DELETE" });
setHamsters(prev => prev.filter(h => h.id !== id));
}
return (
<>
{hamsters.map(hamster => (
<Hamster
key={hamster.id}
hamster={hamster}
onDelete={handleDelete}
/>
))}
</>
);
}
Now you can just make the Hamster component a presentational component that only cares about rendering a hamster, eg:
const Hamster = ({ hamster, onDelete }) => {
const handleDelete = () => onDelete(hamster.id);
return (
<div>
<button onClick={handleDelete}>Delete</button>
<h2>{hamster.name}</h2>
<p>Ålder:{hamster.age}</p>
<p>Favorit mat:{hamster.favFood}</p>
<p>Matcher:{hamster.games}</p>
<img src={'./img/' + hamster.imgName} alt="hamster"/>
</div>
);
};
Tried to search for a similar question but couldn't find any, apologies if I missed one. I am using React Material-UI to create a simple web application. I have an XGrid which lists a number of products and various statistics over a user-selected date range. Each row has a button that the user can click. The idea is that, upon clicking the button, the application calls an API to get relevant information about the product in that row. I would like the info returned from the API to be displayed on a Material-UI modal.
I am getting stuck on how to pass the information from the API to the Modal component and display it. I have a simple example in the code below that is close to what I want to accomplish.
import "./styles.css";
import React from "react";
import { Button, Modal, Typography, Box } from "#material-ui/core";
export default function App() {
const [open, setOpen] = React.useState(false);
const handleClose = () => setOpen(false);
return (
<div className="App">
<Button
variant="outlined"
color="primary"
onClick={() => {
setOpen(true);
(async () => {
let response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
let apiCall = await response.json();
let grouped_data = JSON.parse(apiCall.data);
})();
}}
>
Click Here
</Button>
<Modal open={open} onClose={handleClose}>
<Box>
<Typography>Random Text</Typography>
</Box>
</Modal>
</div>
);
}
In this example, I isolated the code into one single App.js on codesandbox. However, in practice I would have the Button and Modal combined into a separate component file with the API URL passed as a prop to the component. I also used JSONPlaceholder instead of my actual API. Currently, the button displays a modal which says "Random Text". However, I would like it to display the information retrieved using the fetch call.
Also, the table will have thousands of rows so I would like to avoid calling the API until the user actually clicks the button. That way I don't overload the server with thousands of separate API calls every time someone loads the page. I appreciate any help anyone could provide.
You would be better to create a variable to hold the information retrieved from the api, and a common function which would be called from the button click. Something like this:
import "./styles.css";
import React from "react";
import { Button, Modal, Typography, Box } from "#material-ui/core";
export default function App() {
const [open, setOpen] = React.useState(false);
const [data, setData] = React.useState(null);
const handleClose = () => {
setOpen(false);
setData(null);
};
const getData = async (someID) => {
try {
let response = await fetch(
`https://jsonplaceholder.typicode.com/todos/${someID}`
);
let apiCall = await response.json();
let grouped_data = JSON.parse(apiCall.data);
setOpen(true);
setData(grouped_data);
} catch (error) {
//Handle errors
}
};
return (
<div className="App">
<Button
variant="outlined"
color="primary"
onClick={() => {
getData(someID);
}}
>
Click Here
</Button>
<Modal open={open} onClose={handleClose}>
<Box>
<Typography>{data ? data.some_property : ''}</Typography>
</Box>
</Modal>
</div>
);
}
I have a custom hook in my React application which uses a GET request to fetch some data from the MongoDB Database. In one of my components, I'm reusing the hook twice, each using different functions that make asynchronous API calls.
While I was looking at the database logs, I realized each of my GET requests were being called twice instead of once. As in, each of my hooks were called twice, making the number of API calls to be four instead of two. I'm not sure why that happens; I'm guessing the async calls result in re-renders that aren't concurrent, or there's somewhere in my component which is causing the re-render; not sure.
Here's what shows up on my MongoDB logs when I load a component:
I've tried passing an empty array to limit the amount of time it runs, however that prevents fetching on reload. Is there a way to adjust the custom hook to have the API call run only once for each hook?
Here is the custom hook which I'm using:
const useFetchMongoField = (user, id, fetchFunction) => {
const [hasFetched, setHasFetched] = useState(false);
const [data, setData] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
if (!user) return;
try {
let result = await fetchFunction(user.email, id);
setData(result);
setHasFetched(true);
} catch (error) {
setError(error.message);
}
};
if (data === null) {
fetchData();
}
}, [user, id, fetchFunction, data]);
return { data, hasFetched, error };
};
This is one of the components where I'm re-using the custom hook twice. In this example, getPercentageRead and getNotes are the functions that are being called twice on MongoDB (two getPercentageRead calls and two getNotes calls), even though I tend to use each of them once.
const Book = ({ location }) => {
const { user } = useAuth0();
const isbn = queryString.parse(location.search).id;
const { data: book, hasFetched: fetchedBook } = useFetchGoogleBook(isbn);
const { data: read, hasFetched: fetchedPercentageRead } = useFetchMongoField(
user,
isbn,
getPercentageRead
);
const { data: notes, hasFetched: fetchedNotes } = useFetchMongoField(
user,
isbn,
getNotes
);
if (isbn === null) {
return <RedirectHome />;
}
return (
<Layout>
<Header header="Book" subheader="In your library" />
{fetchedBook && fetchedPercentageRead && (
<BookContainer
cover={book.cover}
title={book.title}
author={book.author}
date={book.date}
desc={book.desc}
category={book.category}
length={book.length}
avgRating={book.avgRating}
ratings={book.ratings}
language={book.language}
isbn={book.isbn}
username={user.email}
deleteButton={true}
redirectAfterDelete={"/"}
>
<ReadingProgress
percentage={read}
isbn={book.isbn}
user={user.email}
/>
</BookContainer>
)}
{!fetchedBook && (
<Wrapper minHeight="50vh">
<Loading
minHeight="30vh"
src={LoadingIcon}
alt="Loading icon"
className="rotating"
/>
</Wrapper>
)}
<Header header="Notes" subheader="All your notes on this book">
<AddNoteButton
to="/add-note"
state={{
isbn: isbn,
user: user,
}}
>
<AddIcon color="#6b6b6b" />
Add Note
</AddNoteButton>
</Header>
{fetchedNotes && (
<NoteContainer>
{notes.map((note) => {
return (
<NoteBlock
title={note.noteTitle}
date={note.date}
key={note._noteID}
noteID={note._noteID}
bookID={isbn}
/>
);
})}
{notes.length === 0 && (
<NoNotesMessage>
You don't have any notes for this book yet.
</NoNotesMessage>
)}
</NoteContainer>
)}
</Layout>
);
};
The way you have written your fetch functionality in your custom hook useFetchMongoField you have no flag to indicate that a request was already issued and you are currently just waiting for the response. So whenever any property in your useEffect dependency array changes, your request will be issued a second time, or a third time, or more. As long as no response came back.
You can just set a bool flag when you start to send a request, and check that flag in your useEffect before sending a request.
It may be the case that user and isbn are not set initially, and when they are set they each will trigger a re-render, and will trigger a re-evalution of your hook and will trigger your useEffect.
I was able to fix this issue.
The problem was I was assuming the user object was remaining the same across renders, but some of its properties did in fact change. I was only interested in checking the email property of this object which doesn't change, so I only passed user?.email to the dependency array which solved the problem.
// Hi i am a creating a simple chat Application. In this component ,I am Showing All the messages between users .Everything is working as expected .Now i want when a user receives or sends new message i want it should auto scroll to the last message. Now I want to add this feature
import React from "react";
import { Link } from "react-router-dom";
import { useSelector } from "react-redux";
function ShowMessages() {
const currentUserName = useSelector(
(state) => state.user.currentUser.username
);
const allmessages = useSelector((state) => state.message.allMessage);
const chatWith = useSelector((state) => state.user.chatWith);
const LoggedInUser = currentUserName && currentUserName.split("#")[0];
return (
<>
{allmessages &&
allmessages
.filter((item) => {
console.log("item", item.from, item.to, chatWith.id);
return item.fromto === chatWith.id;
})
.map((item, idx) => (
<li
className={item.direction === "send" ? "replies" : "sent"}
key={idx}
>
<div className="media">
<h5>
{item.messageBody}
</h5>
</div>
</li>
))}
</>
);
}
export default ShowMessages;
Right now you have a component ShowMessages, which renders messages, but in your snippet i can't see any container (perhaps you have it a different component). What i would do is put a ref (by using "useRef") on the container, which holds all of the messages.
And every time any message is added (this could be tracked via useEffect), you can get access to the container via the ref (don't forget to use .current). Then, you can choose how to scroll down from this thread - Scroll to bottom of div?
First answer should work just fine. Just remember, that you get the element by the ref!
I'm using a shorten URL API when the user passes a valid link, i fetch API and render the shortened URL with "map medthod" to make them into a list. It has a btn next to each mapped "shortened URL" where onClick i try to copyToClipboard and change state of btn from Copy to Copied. The problem is currently it only works fine if i have 1 item(on click btn works fine with copyToClipboard) but if i have 2 buttons and i click the very 1st btn to copyToClipboard it's focusing the last item in mapped list and copying the value of (last item) 2nd btn and also setting state for all btns to copied. I also don't understand why i can't see li tags with keys in console when i pass them the keys. can someone help me out. I just want to copyToClipboard that input value of the btn i have clicked. here's what it looks like - image of onCLick of 1st btn 2nd btn gets focus & image of no keys in console & apparently they aren't in a list?
Here is the code below
import { useForm } from "react-hook-form";
import axios from 'axios';
import Loading from '../../images/Ripple-1s-200px.svg';
const Shorten = () => {
// get built in props of react hook form i.e. register,handleSubmit & errors / watch is for devs
const { register, handleSubmit, formState: {errors} } = useForm();
//1. set user original values to pass as params to url
const [link, setLink] = useState('');
//2. set loader initial values to false
const [loading, setLoading] = useState(false);
//3. pass the fetched short link object into an array so we can map
const [displayLinks, setDisplayLinks] = useState([]);
//4. onSubmit form log data into link & showLoader for a breif moment
const onSubmit = (data, event) => {
event.preventDefault();
//puttin data in a variable to pass as url parameter if valid
setLink(data.userLink);
//add loading here after data is set to state
setLoading(!false);
}
//5. fetch the shortened url link using async method to show loading
useEffect(() => {
let unmounted = false;
async function makeGetRequest() {
try {
let res = await axios.get('https://api.shrtco.de/v2/shorten', { params: { url: link } });
//hid loader if u get response from api call
if (!unmounted && res.data.result.original_link) {
setLoading(false);
//add the data to displayLinks array to map
return setDisplayLinks(displayLinks => [...displayLinks, res.data.result]);
}
}
catch (error) {
console.log(error, "inital mount request with no data");
}
}
//invoke the makeGetRequest here
makeGetRequest();
return () => {
unmounted = true;
}
//passing dependency to re-render on change of state value
}, [link]);
//6. intial State of copied or not button
const [copySuccess, setCopySuccess] = useState('Copy');
const inputRef = useRef(null);
//7. onCick of button target it's short url right now it's selecting the last element
const copyToClipboard = (e) => {
e.preventDefault();
inputRef.current.select();
document.execCommand('copy');
// This is just personal preference.
setCopySuccess('Copied');
};
console.log(displayLinks);
return (
<div>
<form onSubmit={handleSubmit(onSubmit)}>
<label></label>
<input
{...register("userLink", {required: "Please add a link"})}
type="url"
id="userLink"
/>
{errors.userLink && <span>{errors.userLink.message}</span>}
<input type="submit" />
</form>
{
loading ?
<div className="loader" id="loader">
<img src={Loading} alt="Loading" />
</div>
: <ul>
{
displayLinks.map((el) => {
return (
<li key={el.code}>
<div>
<h5>{el.original_link}</h5>
</div>
{
/* Logical shortcut for only displaying the
button if the copy command exists */
document.queryCommandSupported('copy') &&
<form>
<input
ref={inputRef}
defaultValue={el.full_short_link}>
</input>
<button onClick={copyToClipboard}>{copySuccess}</button>
</form>
}
</li>
)
})
}
</ul>
}
</div>
)
}
export default Shorten;
Its because you are using a single ref for all the links
You are looping over all the links and giving their <input ref={inputRef} />.So the ref will always be attached to the last link input
Maybe don't use refs and use an alternative copyToClipboard function
like this one
const copyToClipboard = (url) => {
const textField = document.createElement('textarea')
textField.innerText = url
document.body.appendChild(textField)
if (window.navigator.platform === 'iPhone') {
textField.setSelectionRange(0, 99999)
} else {
textField.select()
}
document.execCommand('copy')
textField.remove()
setCopySuccess('Copied');
}
OR
Use a library like react-copy-to-clipboard
Also please go through this link