How to use useEffect on button Click? - javascript

I've to call useEffect / Fetch the data only when user click on Search Button otherwise not fetch the data..
Code:
const App = () => {
const[datas,setDatas] = useState([])
const [space,setSpace] = useState(null)
const [print, setPrint] = useState(false)
function getData(val){
// console.log(val.target.value)
setSpace(val.target.value);
setPrint(false)
}
// console.log(space)
useEffect(() => {
const fecthPosts = async () => {
let initial_url = `http://localhost:4000/search`
let url = initial_url + "?text=" + space
const res = await fetch(url);
const {result} = await res.json();
setDatas(result);
fecthPosts(); //I've to call this fetchPosts() when Btn is CLicked
},[space]);
return(
<div className="App">
{ //Displaying on search
print?
<>
<h2>{space}</h2>
<div>
{datas.map((field) =>
<p>{field.title}</p>
<p>{field.author}</p>
)}
</div>
</>
:null
}
<input type="text" onChange={getData} />
<button onClick={() => { setSpace(true); fetchPosts() }}>search</button>
</div>
)
}
};
export default App;
It's not working Error:
fetchPosts() is not defined...
I've also tried like this:
function trigger(){
useEffect(() => {
const fecthPosts = async () => {
let initial_url = `http://localhost:4000/search`
let url = initial_url + "?text=" + space
const res = await fetch(url);
const {result} = await res.json();
setDatas(result);
fecthPosts(); //I've to call this fetchPosts() when Btn is CLicked
},[space]);
}
<button onClick={() => { setSpace(true); trigger() }}>search</button>
It's not working Error:
React Hook useEffect has unnecessary dependencies:'space'
/PLZZ help to out...

make a separate function for api call and in your UseEffect function just call that function and on Button click function call the Api Function and it fetch data automatically

Use useCallback not useEffect
useCallback is similar to useEffect but is for when a function needs a callback, like what you're doing here onClick. useEffect is used in response to some prop changing not an action taken by a user.

You have to set your fetchPosts outside of the useEffect.
Then, you can use a new state search to track any click on the button.
const App = () => {
const [datas, setDatas] = useState([]);
const [space, setSpace] = useState(null);
const [print, setPrint] = useState(false);
const [search, setSearch] = useState(false);
const fetchPosts = async () => {
let initial_url = `http://localhost:4000/search`;
let url = initial_url + "?text=" + space;
const res = await fetch(url);
const { result } = await res.json();
setDatas(result);
};
function getData(val) {
setSpace(val.target.value);
setPrint(false);
}
useEffect(() => {
fetchPosts(); // fecthPosts is called each time space changed
}, [search]);
return (
<div className="App">
{
//Displaying on search
print ? (
<>
<h2>{space}</h2>
<div>
{datas.map((field) => (
<>
<p>{field.title}</p>
<p>{field.author}</p>
</>
))}
</div>
</>
) : null
}
<input type="text" onChange={getData} />
<button onClick={() => setSearch(!search)}>search</button>
</div>
);
};
export default App;

I initialized shouldFetchData = false. Once the button is clicked, I changed it's value; shouldFetchData = true. Inside useEffect I called fetchPosts() only when shouldFetchData is true.
import React, { useState } from "react";
const App = () => {
const [datas, setDatas] = useState([])
const [shouldFetchData, setShouldFetchData] = useState(false);
const [space, setSpace] = useState(null)
const [print, setPrint] = useState(false)
function getData(val) {
// console.log(val.target.value)
setSpace(val.target.value);
setPrint(false)
}
// console.log(space)
const fecthPosts = async () => {
let initial_url = `http://localhost:4000/search`
let url = initial_url + "?text=" + space
const res = await fetch(url);
const { result } = await res.json();
setDatas(result);
fecthPosts(); //I've to call this fetchPosts() when Btn is CLicked
}
useEffect(() => {
if(shouldFetchData) {
fecthPosts();
}
}, [space]);
return (
<div className="App">
{
print ?
<>
<h2>{space}</h2>
<div>
{datas.map((field) =>
<>
<p>{field.title}</p>
<p>{field.author}</p>
</>
)}
</div>
</>
: null
}
<input type="text" onChange={getData} />
<button onClick={() => {
setSpace(true);
setShouldFetchData(true);
}}>search</button>
</div>
)
};
export default App;
I found a few syntax errors in your code, so I hope I did what you intended.
If This is not the proper way to do this or if there exists a better way, please let me know. I'd be happy to learnšŸ¤—.

Related

Unable to set state in a function

So I was trying to build a server side pagination that works like a static one and I'm almost there, But I've encountered some issues which I cannot seem to solve.
This is what my code looks like
const LiveIndex = (props) => {
const [currentPage, setCurrentPage] = useState(0);
const [isLoading, setLoading] = useState(false);
const startLoading = () => setLoading(true);
const stopLoading = () => setLoading(false);
useEffect(() => {
//After the component is mounted set router event handlers
Router.events.on("routeChangeStart", startLoading);
Router.events.on("routeChangeComplete", stopLoading);
return () => {
Router.events.off("routeChangeStart", startLoading);
Router.events.off("routeChangeComplete", stopLoading);
};
}, []);
const paginationHandler = (page) => {
const currentPath = props.router.pathname;
const currentQuery = props.router.query;
currentQuery.page = currentPage + 1;
props.router.push({
pathname: currentPath,
query: currentQuery,
});
setCurrentPage(currentQuery.page);
};
const backToLastPage = (page) => {
const currentPath = props.router.pathname;
const currentQuery = props.router.query;
currentQuery.page = currentPage - 1;
setCurrentPage(currentQuery.page); // THE code that breaks my code.
props.router.push({
pathname: currentPathh,
query: currentQueryy,
});
};
let content;
if (isLoading) {
content = (
<div>
<h2 class="loading-text">loading.</h2>
</div>
);
} else {
//Generating posts list
content = (
<div className="container">
<h2> Live Games - </h2>
<div className="columns is-multiline">
<p>{props.games.name}</p>
</div>
</div>
);
}
return (
<>
<div className={"container-md"}>
<div>{content}</div>
{props.games.length ? (
<a onClick={() => paginationHandler(currentPage)}> moore </a>
) : (
backToLastPage(currentPage)
)}
</div>
</>
);
};
export async function getServerSideProps({ query }) {
const page = query.page || 1; //if page empty we request the first page
const response = await fetch(
`exampleapi.com?sort=&page=${page}&per_page=10&token`
);
const data = await response.json();
return {
props: {
games: data,
},
};
}
export default withRouter(LiveIndex);
The issue is my backToLastPage does the job well but I'm unable to use setCurrentPage() in that function, Every time I use that I get the following error
Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop
How can I possibly update the value of my currentPage state in the backToLast function
Thank you
You're calling backToLastPage directly in JSX which will be re-rendered/re-called every time. And setCurrentPage (with useState) triggers re-rendering for state changes in backToLastPage.
You can imagine that every time the state changes, your component gets rendered and it will set states again that make infinite renderings for the component.
You can use useEffect to handle props.games changes. That will help you to trigger backToLastPage only once whenever props.games get changed.
React.useEffect(() => {
if(!props.games || !props.games.length) {
backToLastPage(currentPage)
}
},[props.games])
Full modification can be
const LiveIndex = (props) => {
const [currentPage, setCurrentPage] = useState(0);
const [isLoading, setLoading] = useState(false);
const startLoading = () => setLoading(true);
const stopLoading = () => setLoading(false);
useEffect(() => {
//After the component is mounted set router event handlers
Router.events.on("routeChangeStart", startLoading);
Router.events.on("routeChangeComplete", stopLoading);
return () => {
Router.events.off("routeChangeStart", startLoading);
Router.events.off("routeChangeComplete", stopLoading);
};
}, []);
//The main change is here
//It will be triggered whenever `props.games` gets updated
React.useEffect(() => {
if(!props.games || !props.games.length) {
backToLastPage(currentPage)
}
},[props.games])
const paginationHandler = (page) => {
const currentPath = props.router.pathname;
const currentQuery = props.router.query;
currentQuery.page = currentPage + 1;
props.router.push({
pathname: currentPath,
query: currentQuery,
});
setCurrentPage(currentQuery.page);
};
const backToLastPage = (page) => {
const currentPath = props.router.pathname;
const currentQuery = props.router.query;
currentQuery.page = currentPage - 1;
setCurrentPage(currentQuery.page); // THE code that breaks my code.
props.router.push({
pathname: currentPathh,
query: currentQueryy,
});
};
let content;
if (isLoading) {
content = (
<div>
<h2 class="loading-text">loading.</h2>
</div>
);
} else {
//Generating posts list
content = (
<div className="container">
<h2> Live Games - </h2>
<div className="columns is-multiline">
<p>{props.games.name}</p>
</div>
</div>
);
}
return (
<>
<div className={"container-md"}>
<div>{content}</div>
{props.games.length && (
<a onClick={() => paginationHandler(currentPage)}> moore </a>
)}
</div>
</>
);
};
export async function getServerSideProps({ query }) {
const page = query.page || 1; //if page empty we request the first page
const response = await fetch(
`exampleapi.com?sort=&page=${page}&per_page=10&token`
);
const data = await response.json();
return {
props: {
games: data,
},
};
}
export default withRouter(LiveIndex);

Read data from request which just finished

If user type id in input, I'd like to fetch post by specific id typed by user. If not, I'd like to fetch whole array of posts, and then get some id from fetched data. I know it doesn't make sense, but it just only for tests.
It doesn't work, cause useState works asynchronously. I tried few solutions, but all of them looked very ugly.
LIVE DEMO
I received an error:
Cannot read properties of undefined (reading 'id')
Cause setPosts hasn't set yet.
What is the best, clear way to handle this case?
import { useState } from "react";
export default function App() {
const [id, setId] = useState("");
const [post, setPost] = useState(null);
const [posts, setPosts] = useState([]);
const fetchPost = async (id) => {
const res = await axios.get(
`https://jsonplaceholder.typicode.com/posts/${id}`
);
setPost(res.data);
};
const fetchPosts = async () => {
const res = await axios.get(`https://jsonplaceholder.typicode.com/posts`);
setPosts(res.data);
};
const onSubmit = async (e) => {
e.preventDefault();
if (id) {
await fetchPost(id);
} else {
await fetchPosts();
await fetchPost(posts[0].id);
}
};
return (
<div className="App">
<form onSubmit={onSubmit}>
<input type="text" onChange={(e) => setId(e.target.value)} />
<button type="submit">submit</button>
</form>
</div>
);
}
You can treat fetchPosts as a side-effect and wrap fetchPost(posts[0].id) in a useEffect dependant on posts.
Or just use the result directly in onSubmit() (presuming you don't need posts for something else).
const fetchPosts = async () => {
const res = await axios.get(`https://jsonplaceholder.typicode.com/posts`);
// setPosts(res.data); // this state is transitory and not used directly by the render
return res.data;
};
const onSubmit = async (e) => {
e.preventDefault();
if (id) {
await fetchPost(id);
} else {
const posts = await fetchPosts(); // Only used as part of submit event?
await fetchPost(posts[0].id);
}
};
return (
<div className="App">
<form onSubmit={onSubmit}>
<input type="text" onChange={(e) => setId(e.target.value)} />
<button type="submit">submit</button>
</form>
<div>{(post && post.title) || "No post yet"}</div>
</div>
);
Just like you said useState works asynchronously , if you want to do something after mutating it you will have to use useEffect and set posts as its arguments , now whenever the posts get mutated your funcion will be run and the first index of array will be sent to the fetchPost(id),
import axios from "axios";
import "./styles.css";
import { useEffect, useState } from "react";
export default function App() {
const [id, setId] = useState("");
const [post, setPost] = useState(null);
const [posts, setPosts] = useState([]);
useEffect(() => {
if (posts.length) {
fetchPost(posts[0].id);
}
}, [posts]);
const fetchPost = async (id) => {
console.log(`fetching ${id}`);
const res = await axios.get(
`https://jsonplaceholder.typicode.com/posts/${id}`
);
console.log(res.data);
setPost(res.data);
};
const fetchPosts = async () => {
console.log(`fetching all posts`);
const res = await axios.get(`https://jsonplaceholder.typicode.com/posts`);
setPosts(res.data);
};
const onSubmit = async (e) => {
e.preventDefault();
if (id) {
await fetchPost(id);
} else {
await fetchPosts();
// res = await fetchPost(posts[0].id); we dont need it here it defined in useffect function
}
};
const setDefaultId = (e) => {
setId(e.target.value);
};
return (
<div className="App">
<form onSubmit={onSubmit}>
<input type="text" onChange={(e) => setDefaultId(e)} />
<button type="submit">submit</button>
</form>
</div>
);
}
Also consider never to update state directly in your return function it will cause performance issues
The problem is in the method "fetchPost". Inside this method, you have two variables with the same name. "id" from the state hook, and "id" from the function parameter.
You can solve the problem changing one of those variables names.
One more thing, if "id" doesn't have value, your way to get the first post won't work because the await method won't wait to the change of the state.
I have edit a bit the code to solve both problems.
import { useState } from 'react';
import axios from 'axios';
export default function App() {
const [id, setId] = useState('');
const [post, setPost] = useState(null);
const fetchPost = async (idProp) => {
const res = await axios.get(
`https://jsonplaceholder.typicode.com/posts/${idProp}`,
);
setPost(res.data);
};
const fetchPosts = async () => {
const res = await axios.get('https://jsonplaceholder.typicode.com/posts');
await fetchPost(res.data[0].id);
};
const onSubmit = async (e) => {
e.preventDefault();
if (id) {
await fetchPost(id);
} else {
await fetchPosts();
}
};
return (
<div className="App">
<form onSubmit={onSubmit}>
<input type="text" onChange={(e) => {
setId(e.target.value);
}} />
<button type="submit">submit</button>
</form>
</div>
);
}
I hop I've helped you.

There's a bug with Search and Pagination in React

I'm building my site in React and I have created pagination and search. When I search for something on the site, it only works when after that I go to another page. I think this is due to the fact that Softwares and Pagination are in the same component.
Then I tried lifting-state-up, but I got an error: React Minified Error # 31.
Here's Pagination component:
const Paginator = ({
total, // Total records
startPage = 1,
totalPages = null,
onMovePage = null,
}) => {
...
return (
<>
<section id={styles.paginator}>
<Header/>
...
{range(1, totalPages+1).map(p => (
<PagItem key={p} handleClick={ () => {setCurrentPage(p); onMovePage && onMovePage({currentPage: p})} } title={p} name={p} />
))}
...
</section>
</>
);
};
Here's Softwares component:
const Softwares = ({ search }) => {
const [softwares, setSoftwares] = useState([]);
const [total, setTotal] = useState(null);
const [totalPages, setTotalPages] = useState(null);
const [valid, setValid] = useState(false);
const fetchData = async ({ currentPage }) => {
const SEARCH = search ? `?search=${search}` : '';
const CURRENT_PAGE = currentPage && SEARCH === '' ? `?page=${currentPage}` : '';
const response = await fetch(`http://127.0.0.1:8000/api/software/${CURRENT_PAGE}${SEARCH}`);
const data = await response.json();
setSoftwares(data.results);
setTotal(data.count);
setTotalPages(data.total_pages);
setValid(true);
}
useEffect(() => {
fetchData({ currentPage: 1 });
}, []);
return (
<>
{
valid &&
<section className={styles.softwares}>
<Header header={"new softwares"} />
{softwares.map(s => (
<Article key={s.id} pathname={s.id} title={s.title} image={s.image} pubdate={s.pub_date} icon={s.category.parent.img} categoryID={s.category.id} categoryName={s.category.name} dCount={s.counter} content={s.content} />
))}
<Paginator totalPages={totalPages} total={total} onMovePage={fetchData} />
</section>
}
</>
);
};
SearchForm in Header component:
const Header = ({ handleChange, handleClick }) => {
return (
...
<SearchForm handleChange={handleChange} handleClick={handleClick} />
...
);
};
const SearchForm = ({ style, handleChange, handleClick }) => {
return (
<div style={style}>
<form>
<input
type="text"
onChange={handleChange}
/>
<SearchButton onClick={handleClick} />
<small>ENTER</small>
</form>
</div>
);
};
const SearchButton = ({onClick }) => {
return (
<button type="button" onClick={onClick}>
<FontAwesomeIcon icon={faSearch} />
</button>
);
};
And part of Search in App component:
const App = () => {
...
// Search
const [search, setSearch] = useState('');
const [shouldFetch, setShouldFetch] = useState(false);
const handleChange = (e) => {
setSearch(e.target.value);
}
useEffect(() => {
if (shouldFetch) {
(async () => {
const response = await fetch(`http://127.0.0.1:8000/api/software/?search=${search}`);
const data = await response.json();
setShouldFetch(false);
})()
}
}, [shouldFetch]);
const handleClick = () => setShouldFetch(true);
return (
<div className="App">
<Header handleChange={handleChange} handleClick={handleClick} />
...
<Switch>
<Route path="/" exact render={props => <Softwares {...props} search={search} />} />
</Switch>
{/* Actually I'd like to use Paginator here, but it
throws the error: React Minified Error # 31 */}
...
</div>
);
}
So, how can this be done?
The problem is your useEffect dependencies (or lack thereof).
Here's the relevant section of the code:
const Softwares = ({ search }) => {
const [softwares, setSoftwares] = useState([]);
const [total, setTotal] = useState(null);
const [totalPages, setTotalPages] = useState(null);
const [valid, setValid] = useState(false);
const fetchData = async ({ currentPage }) => {
const SEARCH = search ? `?search=${search}` : '';
const CURRENT_PAGE = currentPage && SEARCH === '' ? `?page=${currentPage}` : '';
const response = await fetch(`http://127.0.0.1:8000/api/software/${CURRENT_PAGE}${SEARCH}`);
const data = await response.json();
setSoftwares(data.results);
setTotal(data.count);
setTotalPages(data.total_pages);
setValid(true);
}
useEffect(() => {
fetchData({ currentPage: 1 });
}, []);
The empty dependency array means that you are running the effect that calls fetchData one time when the component mounts. Clicks in the Pagination component will call the fetchData function directly. Changes to search do not cause fetchData to re-run. The data depends on the search so search should be a dependency.
The fetchData function is fine in this component. The state that I would recommend lifting up is to lift the currentPage up from Pagination into Softwares. The onMovePage callback can just update the currentPage state. That way you can call fetchData only through your effect and run the effect whenever either search or currentPage changes.
const Softwares = ({ search }) => {
const [softwares, setSoftwares] = useState([]);
const [total, setTotal] = useState(null);
const [totalPages, setTotalPages] = useState(null);
const [valid, setValid] = useState(false);
const [currentPage, setCurrentPage] = useState(1);
useEffect(() => {
// defining the function inside of the useEffect
// lets eslint exhaustive dependency checks work their magic
const fetchData = async () => {
const SEARCH = search ? `?search=${search}` : '';
const CURRENT_PAGE = currentPage && SEARCH === '' ? `?page=${currentPage}` : '';
const response = await fetch(`http://127.0.0.1:8000/api/software/${CURRENT_PAGE}${SEARCH}`);
const data = await response.json();
setSoftwares(data.results);
setTotal(data.count);
setTotalPages(data.total_pages);
setValid(true);
}
// need to define and call in separate steps when using async functions
fetchData();
}, [currentPage, search]);
return (
...
<Paginator page={currentPage} totalPages={totalPages} total={total} onMovePage={setCurrentPage} />
...
);
};

save data using hooks

I fetch data from goodreads API and save it in books array using hooks.
I need to get data and display in component according to search query. but there is an issue in console (Uncaught TypeError: setSearchText is not a function)
function App() {
const [books, setBooks] = useState([])
const [searchText, setSearchText] = ('')
const key = "xxx"
const url = `https://cors-anywhere.herokuapp.com/` +
`https://www.goodreads.com/search/index.xml?key=${key}&q=${searchText}`;
useEffect (()=> {
loadData()
}, [])
const loadData = async () => {
axios.get(url).then((res) => {
setBooks(res.data)
console.log(books)
})
}
const onTextChange = (e) => {
setSearchText(e.target.value)
}
return (
<>
<Container>
<h1>Bookstore</h1>
<input type='text'
placeholder='Search...'
name="searchText"
onChange={onTextChange}
value={searchText}
/>
</Container>
</>
);
}
You are missing a function call on the right side of the destructuring assignment.
const [books, setBooks] = useState([])
const [searchText, setSearchText] = ('') // This should be useState('')

TypeError: Cannot read property 'filter' of undefined (live searching)

So, i have this code that retrieves movies from api and im trying to implement live searching. I created an if statement to check the input but every time i put the first character in the input field I get the filter undefined error. How can I fix this?
import React, { useState, useEffect } from "react";
const SearchMovie = () => {
const [state, setState] = useState([]);
const [movie, setmovie] = useState("");
const [search, setSearch] = useState("");
const key = "xxxxxxxx";
const url = `http://www.omdbapi.com/?s=${movie}&apikey=${key}`;
useEffect(() => {
getData();
}, [movie]);
const getData = async () => {
const data = await fetch(url);
const response = await data.json();
setState(response.Search);
console.log(response.Search);
};
const updateSearch = (e) => {
setSearch(e.target.value);
};
const getSearch = (e) => {
e.preventDefault();
setmovie(search);
setSearch("");
}
if(search.length > 0) {
setState(state.filter((i)=>{
return i.Title.match(search)
}))
}
return (
<div>
<form onSubmit={getSearch} className="search-form">
<input
type="text"
className="search-bar"
value={search}
onChange={updateSearch}
/>
<button className="search-button" type="submit">
Search
</button>
</form>
{(state || []).map((details) => (
<>
<p>{details.Title}</p>
<p>{details.Year}</p>
<img src={details.Poster} alt=""/>
</>
))}
</div>
);
};
export default SearchMovie;
You have call filter on undefined. Because you have setState(response.Search). I think your result search is undefined. Let's check.
const getData = async () => {
const data = await fetch(url);
const response = await data.json();
setState(response.Search ? response.Search : []);
//or
//if (response.Search) setState(response.Search)
console.log(response.Search);
};

Categories

Resources