React router dom dynamic routing - javascript

I am doing a React.js project. I am retrieving dat from the Star Wars API rendering a list of films on the screen and now I am trying to route every film to its own page through react-router-dom. Unfortunately, I am not able to make it work. it crash when I try to routing dynamically.
UPDATE AFTER ANSWER OF REZA
This is the App.js:
import './App.css';
import { Route, Routes } from "react-router-dom";
import Home from './components/Home';
import ItemContainer from './components/ItemContainer';
import Navbar from './components/Navbar';
function App() {
return (
<>
<Navbar />
<Routes>
<Route exact path='/' element={<Home />} />
<Route exact path="/:movieId" element={<ItemContainer />} />
</Routes>
</>
);
}
export default App;
This is the ItemContainer:
import { useEffect, useState } from "react";
import MovieDetail from "../MovieDetail";
import { useParams } from "react-router-dom";
const ShowMovie = (movieId) => {
const [result, setResult] = useState([]);
const fetchData = async () => {
const res = await fetch("https://www.swapi.tech/api/films/");
const json = await res.json();
setResult(json.result);
}
useEffect(() => {
fetchData();
}, []);
return new Promise((res) =>
res(result.find((value) => value.properties.title === movieId)))
}
const ItemContainer = () => {
const [films, setFilms] = useState([]);
const { movieId } = useParams([]);
console.log('params movieId container', movieId)
useEffect(() => {
ShowMovie(movieId).then((value) => {
setFilms(value.properties.title)
})
}, [movieId])
return (
<MovieDetail key={films.properties.title} films={films} />
);
}
export default ItemContainer;
The console.log doesn't give anything.
UPDATE
Also, this is the whole code in sandbox.

ShowMovie is declared like a React component, but used like a utility function. You shouldn't directly invoke React function components. React functions are also to be synchronous, pure functions. ShowMovie is returning a Promise with makes it an asynchronous function.
Convert ShowMovie into a utility function, which will basically call fetch and process the JSON response.
import { useEffect, useState } from "react";
import MovieDetail from "../MovieDetail";
import { useParams } from "react-router-dom";
const showMovie = async (movieId) => {
const res = await fetch("https://www.swapi.tech/api/films/");
const json = await res.json();
const movie = json.result.find((value) => value.properties.episode_id === Number(movieId)));
if (!movie) {
throw new Error("No match found.");
}
return movie;
}
const ItemContainer = () => {
const [films, setFilms] = useState({});
const { movieId } = useParams();
useEffect(() => {
console.log('params movieId container', movieId);
showMovie(movieId)
.then((movie) => {
setFilms(movie);
})
.catch(error => {
// handle error/log it/show message/ignore/etc...
setFilms({}); // maintain state invariant of object
});
}, [movieId]);
return (
<MovieDetail key={films.properties?.title} films={films} />
);
};
export default ItemContainer;
Update
The route path should include movieId, the param you are accessing in ItemContainer. The sub-path "film" should match what you link from in Home. In Home ensure you link to the /"film/...." path.
<Routes>
<Route path="/films" element={<Home />} />
<Route path="/film/:movieId" element={<ItemContainer />} />
<Route path="/" element={<Navigate replace to="/films" />} />
</Routes>
In ItemContainer you should be matching a movie object's episode_id property to the movieId value. Store the entire movie object into state, not just the title.
const showMovie = async (movieId) => {
const res = await fetch("https://www.swapi.tech/api/films/");
const json = await res.json();
const movie = json.result.find((value) => value.properties.episode_id === Number(movieId)));
if (!movie) {
throw new Error("No match found.");
}
return movie;
}
...
useEffect(() => {
console.log("params movieId container", movieId);
showMovie(movieId)
.then((movie) => {
setFilms(movie);
})
.catch((error) => {
// handle error/log it/show message/ignore/etc...
setFilms({}); // maintain state invariant of object
});
}, [movieId]);
You should also use Optional Chaining on the more deeply nested films prop object properties in MovieDetail, or conditionally render MovieDetail only if the films state has something to display.
const MovieDetail = ({ films }) => {
return (
<div>
<h1>{films.properties?.title}</h1>
<h3>{films.description}</h3>
</div>
);
};
Demo:

Modify App.js like this:
function App() {
return (
<>
<Navbar />
<Routes>
<Route exact path="/" element={<Home />} />
<Route exact path="/MovieDetail/:movieId" element={<ItemContainer />} />
</Routes>
</>
);
}

Related

React search filter form

I have been trying to set a search filter form. I am getting data from API (an array of cake objects with "id", "cake_name", "category" etc properties), these get displayed properly. But somehow my search function is not working? It should allow the user to input a name of a cake which then would be filtered through the cakes available and only the searched one(s) would be displayed.
I am getting this error:
error
Here is my code:
context.js:
import React, { useState, useContext, useEffect } from "react";
import { useCallback } from "react";
const url = "https://cakeaddicts-api.herokuapp.com/cakes";
const AppContext = React.createContext();
const AppProvider = ({ children }) => {
const [loading, setLoading] = useState(false);
const [searchTerm, setSearchTerm] = useState("");
const [cakes, setCakes] = useState([]);
const [filteredData, setFilteredData] = useState([]);
const fetchCakes = async () => {
setLoading(true);
try {
const response = await fetch(url);
const cakes = await response.json();
if (cakes) {
const newCakes = cakes.map((cake) => {
const {
id,
image,
cake_name,
category,
type,
ingredients,
instructions,
} = cake;
return {
id,
image,
cake_name,
category,
type,
ingredients,
instructions,
};
});
setCakes(newCakes);
console.log(newCakes);
} else {
setCakes([]);
}
setLoading(false);
} catch (error) {
console.log(error);
setLoading(false);
}
};
useEffect(() => {
fetchCakes();
}, []);
return (
<AppContext.Provider
value={{
loading,
cakes,
setSearchTerm,
searchTerm,
filteredData,
setFilteredData,
}}
>
{children}
</AppContext.Provider>
);
};
// make sure use
export const useGlobalContext = () => {
return useContext(AppContext);
};
export { AppContext, AppProvider };
SearchForm.js
import React from "react";
import { useGlobalContext } from "../context";
import CakeList from "./CakeList";
const SearchForm = () => {
const { cakes, setSearchTerm, searchTerm, setFilteredData } =
useGlobalContext;
const searchCakes = () => {
if (searchTerm !== "") {
const filteredData = cakes.filter((item) => {
return Object.values(item)
.join("")
.toLowerCase()
.includes(searchTerm.toLowerCase());
});
setFilteredData(filteredData);
} else {
setFilteredData(cakes);
}
};
return (
<section className="section search">
<form className="search-form">
<div className="form-control">
<label htmlFor="name">Search Your Favourite Cake</label>
<input
type="text"
id="name"
onChange={(e) => searchCakes(e.target.value)}
/>
</div>
</form>
</section>
);
};
export default SearchForm;
CakeList.js:
import React from "react";
import Cake from "./Cake";
import Loading from "./Loading";
import { useGlobalContext } from "../context.js";
const CakeList = () => {
const { cakes, loading, searchTerm, filteredResults } = useGlobalContext();
if (loading) {
return <Loading />;
}
return (
<section className="section">
<h2 className="section-title">Cakes</h2>
<div className="cakes-center">
{searchTerm.length > 1
? filteredResults.map((cake) => {
return <Cake key={cake.id} {...cake} />;
})
: cakes.map((item) => {
return <Cake key={item.id} {...item} />;
})}
</div>
</section>
);
};
export default CakeList;
App.js:
import React from "react";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
// import pages
import Home from "./pages/Home";
import About from "./pages/About";
import SingleCake from "./pages/SingleCake";
import Error from "./pages/Error";
// import components
import Navbar from "./components/Navbar";
function App() {
return (
<Router>
<Navbar />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/cake/:id" element={<SingleCake />} />
<Route path="*" element={<Error />} />
</Routes>
</Router>
);
}
export default App;
Can someone please help me with this search form? I have tried so many things and nothing is working :( Anyone?
On line 11 of SearchForm.js, there is a part that reads cakes.filter(. To resolve the typeError, change this to cakes?.filter(. This will only execute the filter if cakes is defined. It's a feature in javascript called Optional Chaining, introduced in ES2020.
Learn about it more here

REACT - how can wait until api call finish to load a path?

I use the axios post to request to the back-end if the user have access to the application. The problem is the axios returns undefined and then true or false . Have a private Route to manage what to do in case returns true or false (in this case undefined = false) ,is axios the problem or is there some other way? like wait until returns true or false
IsLogin.jsx
import React from 'react'
const axios = require('axios');
export const AuthContext = React.createContext({})
export default function Islogin({ children }) {
const isAuthenticated =()=>{
try{
axios.post('/api/auth').then(response => {
var res = response.data.result;
console.log(res)
return res
})
} catch (error) {
console.error(error);
return false
}
}
var auth = isAuthenticated()
console.log(auth);
return (
<AuthContext.Provider value={{auth}}>
{children}
</AuthContext.Provider>
)
}
privateRoute.js
import React, { useContext } from 'react';
import { Route, Redirect } from 'react-router-dom';
import {AuthContext} from '../utils/IsLogin';
const PrivateRoute = ({component: Component, ...rest}) => {
const {isAuthenticated} = useContext(AuthContext)
return (
// Show the component only when the user is logged in
// Otherwise, redirect the user to /unauth page
<Route {...rest} render={props => (
isAuthenticated ?
<Component {...props} />
: <Redirect to="/unauth" />
)} />
);
};
export default PrivateRoute;
app.js
class App extends Component {
render() {
return (
<>
<BrowserRouter>
<Islogin>
<Header/>
<Banner/>
<Switch>
<PrivateRoute exact path="/index" component={Landing} />
<PrivateRoute path="/upload" component={Upload} exact />
<PublicRoute restricted={false} path="/unauth" component={Unauthorized} exact />
</Switch>
</Islogin>
</BrowserRouter>
</>
);
}
}
You don't want to return anything in your post request. You should be updating your context store
const isAuthenticated = () => {
try {
axios.post('/api/auth').then(response => {
var res = response.data.result;
console.log(res)
// update your context here instead of returning
return res
})
} catch (error) {
console.error(error);
return false
}
}
In your private route, have a componentDidUpdate style useEffect hook to check for changes in authentication status and update an internal flag on an as-needed basis
const PrivateRoute = ({ component: Component, ...rest }) => {
const { isAuthenticated } = useContext(AuthContext)
const [validCredentials, setValidCredentials] = React.useState(false)
React.useEffect(() => {
if (typeof isAuthenticated === 'boolean') {
setValidCredentials(isAuthenticated)
}
}, [isAuthenticated])
return (
// Show the component only when the user is logged in
// Otherwise, redirect the user to /unauth page
<Route {...rest} render={props => (
validCredentials ?
<Component {...props} />
: <Redirect to="/unauth" />
)} />
);
};
I am curious as to why you didn't use 'async await',lol.
You are making a post request to the endpoint '/api/auth',but you didn't give it any data to post,like:
try{
axios.post('/api/auth',{username,password}).then(response => {
var res = response.data.result;
console.log(res)
return res
})
} catch (error) {
console.error(error);
return false
}

Error: Too many re-renders. React limits the number of renders to prevent an infinite loop

How do I prevent the following error:
Too many re-renders. React limits the number of renders to prevent an infinite loop.'
I just changed a class based component to functional component and its not working
My source code
import React, {Fragment, useState} from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import Navbar from './Components/Layout/Navbar';
import Users from './Components/users/Users';
import User from './Components/users/User';
import Search from './Components/users/Search';
import Alert from './Components/Layout/Alert';
import About from './Components/pages/About';
import './App.css';
import Axios from 'axios';
const App = () => {
const [users, setUsers] = useState( [] );
const [user, setUser] = useState( {} );
const [repos, setRepos] = useState( [] );
const [loading, setLoading] = useState( false );
const [alert, setAlert] = useState( null );
// Search Github Users
const searchUsers = async text => {
setLoading(true);
const res = await Axios.get(`https://api.github.com/search/users?q=${text}&client_id=${process.env.REACT_APP_GITHUB_CLIENT_ID}&client_secret=${process.env.REACT_APP_GITHUB_CLIENT_SECRET}`);
setUsers(res.data.items);
setLoading(false);
};
// GEt single github user
const getUser = async username => {
setLoading(true);
const res = await Axios.get(`https://api.github.com/users/${username}?&client_id=${process.env.REACT_APP_GITHUB_CLIENT_ID}&client_secret=${process.env.REACT_APP_GITHUB_CLIENT_SECRET}`);
setUser(res.data);
setLoading(false);
};
// Get users repos
const getUserRepos = async username => {
setLoading(true);
const res = await Axios.get(`https://api.github.com/users/${username}/repos?per_page=5&sort=created:asc&client_id=${process.env.REACT_APP_GITHUB_CLIENT_ID}&client_secret=${process.env.REACT_APP_GITHUB_CLIENT_SECRET}`);
setRepos(res.data);
setLoading(false);
};
// Clear users from state
const clearUsers = () =>
setUsers([]);
setLoading(false);
// Set ALert
const showAlert = (msg, type) => {
setAlert({msg, type});
setTimeout(()=> setAlert(null),3000);
};
return (
<Router>
<div className="App">
<Navbar />
<div className="container">
<Alert alert={alert} />
<Switch>
<Route exact path='/' render={props => (
<Fragment>
<Search
searchUsers={searchUsers}
clearUsers={clearUsers}
showClear={ users.length>0? true : false }
setAlert={showAlert}
/>
<Users loading={loading} users={users} />
</Fragment>
)} />
<Route exact path = '/about' component={About} />
<Route exact path= '/user/:login' render={props => (
<User
{...props}
getUser={getUser}
getUserRepos={getUserRepos}
user={user}
repos={repos}
loading={loading} />
)} />
</Switch>
</div>
</div>
</Router>
);
}
export default App;
I just change a class based component to functional component and i get these error.
0
How do I prevent the following error:
Too many re-renders. React limits the number of renders to prevent an infinite loop.'
As from the comment,
There was error in the declaration of function clearUsers
const clearUsers = () => setUsers([]);
setLoading(false);
which should be.
const clearUsers = () => {
setUsers([]);
setLoading(false);
}
because of this small typo. The setLoading function was being called on the first render which would then call setLoading triggering react to call render again and in return call setLoading and caused the infinite renders.
I experienced the same error. I found my problem was having brackets at the end of a function(). Yet the function should have been called without brackets. Rookie error.
Before:
onClick={myFunction()}
After:
onClick={myFunction}
If you are using a button also check the caps of your 'onclick'.

TypeError: Cannot read property 'map' of undefined when trying to useLocalStorage instead of useState

I am trying to use a local storage hook on one of my components, I am receiving "list" is undefined despite passing it down as a prop. First codeblock is my App.js, second codeblock is my component. I had this working briefly by passing an empty object into my useLocalStorage hook, but can't figure out how I broke it :)
TypeError: Cannot read property 'map' of undefined
import React, { useState, useEffect } from "react";
import { Route } from "react-router-dom";
import SavedList from "./Movies/SavedList";
import MovieList from "./Movies/MovieList";
import Movie from "./Movies/Movie";
import axios from 'axios';
import UpdateForm from "./Movies/UpdateForm"
import useLocalStorage from "./hooks/useLocalStorage"
const App = () => {
const [savedList, setSavedList] = useLocalStorage();
const [movieList, setMovieList] = useState([]);
const getMovieList = () => {
axios
.get("http://localhost:5000/api/movies")
.then(res => setMovieList(res.data))
.catch(err => console.log(err.response));
};
const addToSavedList = movie => {
setSavedList([...savedList, movie])
}
useEffect(() => {
getMovieList();
}, []);
const setMovie = updatedMovie => {
const updatedMovies = [...movieList];
const index = updatedMovies.findIndex(item => item.id === updatedMovie.id);
updatedMovies[index] = updatedMovie;
setMovieList(updatedMovies);
};
const deleteMovies = deletedMovie => {
const newMovies = [...movieList];
const filteredMovies = newMovies.filter(item => item.id !== deletedMovie)
setMovieList(filteredMovies);
};
return (
<>
<SavedList list={savedList} />
<Route exact path="/">
<MovieList movies={movieList} />
</Route>
<Route path="/movies/:id">
<Movie addToSavedList={addToSavedList} deleteMovies={deleteMovies} />
</Route>
<Route exact path="/update-movie/:id"
render={props => <UpdateForm {...props} movies={movieList} setMovie={setMovie} /> } />
</>
);
};
export default App;
here is my SavedList component
import { NavLink, Link } from 'react-router-dom';
function SavedList({ list }) {
return (
<div className="saved-list">
<h3>Saved Movies:</h3>
{list.map(movie => {
return (
<NavLink
to={`/movies/${movie.id}`}
key={movie.id}
activeClassName="saved-active"
>
<span className="saved-movie">{movie.title}</span>
</NavLink>
);
})}
<div className="home-button">
<Link to="/">Home</Link>
</div>
</div>
);
}
export default SavedList;
Try passing the key and initial value
const [savedList, setSavedList] = useLocalStorage('savedlist',[])

Redirecting using useEffect hook

The idea is that I've got a component that renders something but in the meantime is checking something that will return or redirect to another component:
useEffect(() => {
(() => {
if (true) {
// return to one component
}
// return to another component
})();
});
return (
<div> Javier </div>
);
I think that it is possible using the useEffect hook, but the problem is that, it does not redirect to my components, I tried using Redirect from the react-router, returning the component itself, and also using the history package, in this case, only replaced the url but no redirection at all.
Is this possible? Or maybe I'm way off the point.
Thanks a lot!
if you are just needing conditional rendering you could do something like this:
const LoadingComponent = () => <div> Javier </div>
function Landing(props) {
const [state={notLoaded:true}, setState] = useState(null);
useEffect(() => {
const asyncCallback = async () =>{
const data = await axios.get('/someApiUrl')
setState(data)
}
asyncCallback()
},[]);
if(!state){
return <FalseyComponent />
}
if(state.notLoaded){
//return some loading component(s) (or nothing to avoid flicker)
return <LoadingComponent /> // -or- return <div/>
}
return <TruthyComponent />
}
or redirect completely:
const LoadingComponent = () => <div> Javier </div>
function Landing(props) {
const [state={notLoaded:true}, setState] = useState(null);
useEffect(() => {
const asyncCallback = async () =>{
const data = await axios.get('/someApiUrl')
setState(data)
}
asyncCallback()
},[]);
if(!state){
return <Redirect to='/falseyRoute' />
}
if(state.notLoaded){
//return some loading component(s) or (nothing to avoid flicker)
return <LoadingComponent /> // -or- return <div/>
}
return <Redirect to='/truthyRoute' />
}
Using React router v6 you can create a redirection using useEffect:
import React, { useEffect } from 'react';
import {
BrowserRouter, Route, Routes, useNavigate,
} from 'react-router-dom';
const App = () => (
<div>
<BrowserRouter>
<Routes>
<Route path="/" element={<Main />} />
<Route path="/home" element={<Home />} />
</Routes>
</BrowserRouter>
</div>
);
const Main = () => {
const navigate = useNavigate();
useEffect(() => {
let didCancel = false;
const goToHomePage = () => navigate('/home');
if (!didCancel) { goToHomePage(); }
return () => { didCancel = true; };
}, [navigate]);
return (
<div>
<h1>Welcome Main!</h1>
</div>
);
};
const Home = () => (
<div>
<h1>Welcome Home!</h1>
</div>
);
export default App;
If you want to create an alternative redirection to another component, you can do it as below:
import React, { useEffect } from 'react';
import {
BrowserRouter, Route, Routes, useNavigate,
} from 'react-router-dom';
const App = () => (
<div>
<BrowserRouter>
<Routes>
<Route path="/" element={<Main />} />
<Route path="/home" element={<Home />} />
<Route path="/other" element={<Other />} />
</Routes>
</BrowserRouter>
</div>
);
const Main = () => {
const navigate = useNavigate();
useEffect(() => {
let didCancel = false;
const goToHomePage = () => navigate('/home');
const goToOtherPage = () => navigate('/other');
if (!didCancel) { goToHomePage(); } else { goToOtherPage(); }
return () => { didCancel = true; };
}, [navigate]);
return (
<div>
<h1>Welcome Main!</h1>
</div>
);
};
const Home = () => (
<div>
<h1>Welcome Home!</h1>
</div>
);
const Other = () => (
<div>
<h1>Welcome Other!</h1>
</div>
);
export default App;
In React router 5 with changed old syntax it should also work. However, in React router 6 I did not find Redirect so the above redirection is more useful.
Try to return based on some state value like this.
import { Redirect } from "react-router-dom"; //import Redirect first
const [redirctTo, setRedirctTo] = useState(false); // your state value to manipulate
useEffect(() => {
(() => {
if (true) {
setRedirctTo(true)
}
// return to another component
})();
});
if(redirctTo){
return <Redirect to="/your-url" />
} else {
return (
<div> Javier </div>
);
}

Categories