Extract Data from API and show in another page - reactjs

This question may sound silly to some people, but I am really confused on how to do it
I have 3 file: App.js, HomePage.js and Profile.js
App.js :
import React from "react"
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import HomePage from "./components/HomePage";
import Profile from "./components/Profile"
function App() {
return (
<Router>
<Switch>
<Route path="/" exact component={HomePage} />
<Route exact path="/profile/:profileId" component= {Profile} />
</Switch>
</Router>
);
}
export default App;
From here, the default page it will go to is HomePage.js
HomePage.js:
import React, { Component } from "react";
import axios from "axios";
import { Link } from "react-router-dom";
class HomePage extends Component {
constructor() {
super();
this.state = {
userData: [],
}
}
componentDidMount() {
axios.get("XXXXXXXX").then((response) => {
const userDataList = response.data.users;
this.setState({
userData: userDataList
})
})
}
render() {
const userGrid = this.state.userData.map((user, index) => {
return (
<div key={index}>
<Link to={`/profile/${user.id}`}>
<img src={user.profilepicture} />
<p>{user.name}</p>
</Link>
</div>
)
})
return (
<div className="App">
<div className="card">
<div className="card__top">
<span className="card__title">
<p>Select An Account</p>
</span>
</div>
<div className="card__bottom">
<div className="card__table">
{userGrid}
</div>
</div>
</div>
</div>
)
}
}
export default HomePage;
In HomePage.js, I am able to show the profile picture and name of the user from API.
In the next page which is Profile.js , I am able to print the ID of the user.
Profile.js:
import React, { Component } from "react";
class Profile extends Component{
componentDidMount(){
const uid = this.props.match.params.profileId;
}
render() {
console.log(this.props.match);
return(
<h1>{this.props.match.params.profileId}</h1>
)
}
}
export default Profile;
As you can see I am printing the ID of user.
Here I also want to show the Profile Picture of the user which I selected in HomePage.js
This I am not able to do it.
JSON file:
{ - users: [-{id:1, name:"abc", profilepicture: "xxxxx.jpeg"}, ]}

You need to store a global state in your applicattion, which you can access from every connected component. This is a more complex topic. redux is a good framework to handle your global state changes.
Here is a tutorial: https://appdividend.com/2018/06/14/how-to-connect-react-and-redux-with-example/
I found it pretty hard to learn redux, but in the end it takes away a lot of pain. Because this is a problem you gonna have in every app you build with react.

You need use Context API o redux
Example context API: https://ibaslogic.com/react-context-api/
Context's well to little projects, but Redux performs better.

App.js
import React from "react"
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import HomePage from "./components/HomePage";
import Profile from "./components/Profile"
import { UsersProvider } from "./UsersProvider.js";
function App() {
return (
<Router>
<UsersProvider>
<Switch>
<Route path="/" exact component={HomePage} />
<Route exact path="/profile/:profileId" component= {Profile} />
</Switch>
</UsersProvider>
</Router>
);
}
export default App;
UsersContext.js
import React, { Component } from "react"
const UsersContext = React.createContext();
const UsersProvider = UsersContext.Provider;
const UsersConsumer = TodosContext.Consumer;
class MyContext extends Component {
state = {
value: null,
};
setValue = (value) => {
this.setState({ value });
};
render() {
return (
<UsersProvider value={{ setValue, value }}>{this.props.children}
</UsersProvider>
)
}
}
export { UsersContext, UsersProvider, UsersConsumer }
HomePage.js
import React, { Component } from "react";
import axios from 'axios';
class HomePage extends Component {
componentDidMount() {
axios.get("XXXXXXXX").then((response) => {
const userDataList = response.data.users;
// updating your context
this.props.context.setValue(userDataList);
})
}
render() {
const userGrid = this.props.context.value.map((user, index) => {
return (
<div key={index}>
<Link to={`/profile/${user.id}`}>
<img src={user.profilepicture} />
<p>{user.name}</p>
</Link>
</div>
)
})
return (
<div className="App">
<div className="card">
<div className="card__top">
<span className="card__title">
<p>Select An Account</p>
</span>
</div>
<div className="card__bottom">
<div className="card__table">
{userGrid}
</div>
</div>
</div>
</div>
)
}
}
export default HomePage;
Profile.js
import React, { Component } from "react";
import { UsersConsumer } from "./UsersContext.js";
class Profile extends Component{
render() {
return(
<UsersConsumer>
{users => (
<h1>{users.value.find(user => user.id === this.props.match.params.profileId)}</h1>
)}
</UsersConsumer>
)
}
}
export default Profile;

Related

How do you access match in a React-Redux container?

Firstly, thank you to anyone who is reading this and is willing to help!
I'm trying to build a react-redux web app, and I'm having trouble accessing an id from the url in a container. The url looks like this: websitename.com/games/:game_id
I need to access that :game_id so that I can use it in a redux action to make a call to my api, but I can't figure out how to access the usage of match. I get the following error when I try to compile:
./src/containers/GameDetails.js
Line 9:19: 'match' is not defined no-undef
My app is set up with the following structure: Main.js houses the routes:
import React from "react";
import {Switch, Route, withRouter, Redirect} from "react-router-dom";
import {connect} from "react-redux";
import Homepage from "../components/Homepage";
import AuthForm from "../components/AuthForm";
import {authUser} from "../store/actions/auth";
import {removeError} from "../store/actions/errors"
import withAuth from "../hocs/withAuth";
import GameForm from "./GameForm";
import GamePage from "../components/GamePage";
const Main = props => {
const {authUser, errors, removeError, currentUser} = props;
return (
<div className="container">
<Switch>
<Route path="/" exact render={props => <Homepage currentUser={currentUser} {...props} /> } />
<Route
path="/signin" exact
render={props => {
return(
<AuthForm
removeError={removeError}
errors={errors}
onAuth={authUser}
buttonText="Log in"
heading="Welcome Back."
{...props}
/>
)
}} />
<Route
path="/signup" exact
render={props => {
return(
<AuthForm
removeError={removeError}
errors={errors}
onAuth={authUser}
signUp
buttonText="Sign me up"
heading="Join Weekly Matchup today."
{...props}
/>
)
}}
/>
<Route
path="/games/new" exact
component={withAuth(GameForm)}
/>
<Route
path="/games/:game_id"
render={props => {
return(
<GamePage
currentUser={currentUser}
{...props}
/>
)
}}
/>
<Redirect to="/" />
</Switch>
</div>
)
}
function mapStateToProps(state){
return {
currentUser: state.currentUser,
errors: state.errors
};
}
export default withRouter(connect(mapStateToProps, {authUser, removeError})(Main));
GamePage.js is a component that has the GameDetails container in it:
import React from "react";
import { Link } from "react-router-dom";
import GameDetails from "../containers/GameDetails";
const GamePage = ({ currentUser }) => {
if (!currentUser.isAuthenticated) {
return (
<div className="home-hero">
<h1>You must sign in or sign up in order to vote for matchups and view comments.</h1>
</div>
);
}
return (
<div>
<div className="home-hero">
<GameDetails />
</div>
</div>
)
}
export default GamePage;
And GameDetails.js is where I'm trying to get the id from the url to use in my redux action:
import React, { Component } from "react";
import { connect } from "react-redux";
import { Link } from "react-router-dom";
import { getGameDetails } from "../store/actions/games";
class GameDetails extends Component {
componentDidMount() {
const game_id = match.params.game_id;
this.props.getGameDetails(game_id);
}
render() {
const { match, game } = this.props;
return (
<div className="home-hero">
<div className="offset-1 col-sm-10">
<h4>You are viewing the Game Page for game.title</h4>
</div>
</div>
);
}
}
function mapStateToProps(state) {
return {
game: state.game
};
}
export default connect(mapStateToProps, { getGameDetails })(
GameDetails
);
I'm still very new to react and redux, so I appreciate any help you can offer.
Thank you for your time and patience!
Try something like this in GameDetails.js and GamePage.js
import React from "react";
import { Link } from "react-router-dom";
import GameDetails from "../containers/GameDetails";
const GamePage = ({ currentUser, ...props }) => {
if (!currentUser.isAuthenticated) {
return (
<div className="home-hero">
<h1>You must sign in or sign up in order to vote for matchups and view comments.</h1>
</div>
);
}
return (
<div>
<div className="home-hero">
<GameDetails {...props} />
</div>
</div>
)
}
export default GamePage;
import React, { Component } from "react";
import { connect } from "react-redux";
import { Link } from "react-router-dom";
import { getGameDetails } from "../store/actions/games";
class GameDetails extends Component {
componentDidMount() {
const {game_id}= this.props.match.params.game_id;
this.props.getGameDetails(game_id);
}
render() {
const { match, game } = this.props;
return (
<div className="home-hero">
<div className="offset-1 col-sm-10">
<h4>You are viewing the Game Page for game.title</h4>
</div>
</div>
);
}
}
function mapStateToProps(state) {
return {
game: state.game
};
}
export default connect(mapStateToProps, { getGameDetails })(
GameDetails
);
I suppose you use you exported component same thing like
<Route path="/games/:game_id" component={GameDetails} />
mapStateToProps get 2 arguments state, and ownProps.
function mapStateToProps(state, ownProps) {
const { match: { params: { game_id } } } = ownProps; // you able to use game_id inside mapStateToProps
return ({ game: state.game });
}
1 solution
import React from "react";
import { Link } from "react-router-dom";
import GameDetails from "../containers/GameDetails";
const GamePage = ({ currentUser, ...routeProps }) => {
if (!currentUser.isAuthenticated) {
return (
<div className="home-hero">
<h1>You must sign in or sign up in order to vote for matchups and view comments.</h1>
</div>
);
}
return (
<div>
<div className="home-hero">
<GameDetails {...routeProps} />
</div>
</div>
)
}
export default GamePage;
2 solution
import React, { Component } from "react";
import { connect } from "react-redux";
import { Link, withRouter } from "react-router-dom";
import { getGameDetails } from "../store/actions/games";
class GameDetails extends Component {
componentDidMount() {
const game_id = match.params.game_id;
this.props.getGameDetails(game_id);
}
render() {
const { match, game } = this.props;
return (
<div className="home-hero">
<div className="offset-1 col-sm-10">
<h4>You are viewing the Game Page for game.title</h4>
</div>
</div>
);
}
}
function mapStateToProps(state) {
return {
game: state.game
};
}
export default withRouter(
connect(mapStateToProps, { getGameDetails })(GameDetails)
);

Not able to open screen in reactjs.Routing not working

I am new to react and trying below link to get started.
https://jasonwatmore.com/post/2018/09/11/react-basic-http-authentication-tutorial-example
But, my screen is not showing any thing and there is not such error on CLI after npm start.
Below is index.js.
import React from 'react';
import { render } from 'react-dom';
import { App } from './App/App.js';
// setup fake backend
import { configureFakeBackend } from './_helpers/fake-backend.js';
configureFakeBackend();
render(
<App />,
document.getElementById('app')
);
App.js
import React from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import { PrivateRoute } from '../_components/PrivateRoute.js';
import { HomePage } from '../HomePage/Homepage.js';
import { LoginPage } from '../LoginPage';
class App extends React.Component {
render() {
return (
<div className="jumbotron">
<div className="container">
<div className="col-sm-8 col-sm-offset-2">
<Router>
<div>
<PrivateRoute path="/" exact component={HomePage} />
<Route path="/login" exact component={LoginPage} />
</div>
</Router>
</div>
</div>
</div>
);
}
}
export { App };
It is just opening a blank half opened screen.
Below is CLI screen shot.
Below are home and login.js code.
import React from 'react';
import { Link } from 'react-router-dom';
import { userService } from '../_services/user.service.js';
class HomePage extends React.Component {
constructor(props) {
super(props);
this.state = {
user: {},
users: []
};
}
componentDidMount() {
this.setState({
user: JSON.parse(localStorage.getItem('user')),
users: { loading: true }
});
userService.getAll().then(users => this.setState({ users }));
}
render() {
const { user, users } = this.state;
return (
<div className="col-md-6 col-md-offset-3">
alert("I am 2nd here");
<h1 >Hi {user.firstName}!</h1>
<p>You're logged in with React & Basic HTTP Authentication!!</p>
<h3>Users from secure api end point:</h3>
{users.loading && <em>Loading users...</em>}
{users.length &&
<ul>
{users.map((user, index) =>
<li key={user.id}>
{user.firstName + ' ' + user.lastName}
</li>
)}
</ul>
}
<p>
<Link to="/login">Logout</Link>
</p>
</div>
);
}
}
export { HomePage };
And output screen is :

Show search result component in another route

I am working with the MovieDB API. I want to show now playing movies on the root route but search result in another route.
I have tried putting history.push() method in handlesubmit but it shows error. Here's the code. Currently I am showing search result component in the home page itself.
App.js
import React, { Component } from "react";
import "./App.css";
import { BrowserRouter, Link, Switch, Route } from "react-router-dom";
import Nav from "./component/Nav";
import axios from "axios";
import { Provider } from "./context";
import Home from "./component/Home";
import SearchResult from "./component/SearchResult";
import MovieDetails from "./component/movieDetails";
class App extends Component {
state = {
movieList: [],
searchResult: [],
currentpage: 1,
totalpage: 1,
API_KEY: "c51081c224217a3989b0bc0c4b3d3fff"
};
componentDidMount() {
this.getCurrentMovies();
}
getCurrentMovies = e => {
axios
.get(
`https://api.themoviedb.org/3/movie/now_playing?api_key=${
this.state.API_KEY
}&language=en-US&page=${this.state.currentpage}`
)
.then(res => {
this.setState({
movieList: res.data.results,
currentpage: res.data.page,
totalpage: res.data.total_pages
});
console.log(this.state);
});
};
getMovies = e => {
e.preventDefault();
const moviename = e.target.elements.moviename.value;
axios
.get(
`https://api.themoviedb.org/3/search/movie?api_key=${
this.state.API_KEY
}&query=${moviename}`
)
.then(res => {
this.setState({
searchResult: res.data.results
});
console.log(this.state.searchResult);
});
console.log(this.router);
};
nextPage = () => {
this.setState(
{
currentpage: (this.state.currentpage += 1)
},
() => console.log(this.state.currentpage)
);
this.getCurrentMovies();
};
prevPage = () => {
if (this.state.movieList && this.state.currentpage !== 1) {
this.setState(
{
currentpage: (this.state.currentpage -= 1)
},
() => console.log(this.state.currentpage)
);
this.getCurrentMovies();
}
};
render() {
const contextProps = {
myState: this.state,
getMovies: this.getMovies,
nextPage: this.nextPage,
prevPage: this.prevPage,
};
return (
<Provider value={contextProps}>
<BrowserRouter>
<Nav />
<Switch>
<Route exact path="/" component={Home} />
<Route path="/:id" component={MovieDetails} />
</Switch>
</BrowserRouter>
</Provider>
);
}
}
export default App;
Home.js
import React, { Component } from "react";
import NowPlaying from "./NowPlaying";
import SearchResult from "./SearchResult";
import SearchBox from "./SearchBox";
class Home extends Component {
state = {};
render() {
return (
<div>
<SearchBox />
<SearchResult />
<NowPlaying />
</div>
);
}
}
export default Home;
SearchBox.js
import React, { Component } from "react";
import { MyContext } from "../context";
import { withRouter } from "react-router-dom";
class SearchBox extends Component {
static contextType = MyContext;
render() {
return (
<React.Fragment>
<div className="jumbotron jumbotron-fluid">
<div className="container" style={{ textAlign: "center" }}>
<h1 className="display-4">Find your Movie</h1>
<p className="lead">
Find rating, descrips and much more of your fev. movie.
</p>
<form onSubmit={this.context.getMovies}>
<input
name="moviename"
className="form-control mr-sm-2"
type="search, submit"
placeholder="Search"
aria-label="Search"
style={{ height: "50px" }}
/>
</form>
</div>
</div>
<div />
</React.Fragment>
);
}
}
export default withRouter(SearchBox);
SearchResult.js
import React, { Component } from "react";
import Movie from "./movie";
import { withRouter } from "react-router-dom";
import { MyContext } from "../context";
import SearchBox from "./SearchBox";
class SearchResult extends Component {
static contextType = MyContext;
render() {
return (
<React.Fragment>
<div className="container">
<div className="row justify-content-center">
{this.context.myState.searchResult.map(movie => {
return <Movie id={movie.id} image={movie.poster_path} />;
})}
</div>
{/* <button>Prev</button>
<button>Next</button> */}
</div>
</React.Fragment>
);
}
}
export default SearchResult;
and another thing. The pagination works for Now Playing Movies but couldn't make it to work with search result. Please help.
You can pass data with Redirect like this:
<Redirect to={{
pathname: '/movies',
state: { id: '123' }
}}
/>
and this is how you can access it:
this.props.location.state.id

prop returns Null when component renders

I am trying to add some functionality that enables or disables a button depending on whether the user has at least one "credit". I want to use the logical && to determine whether to enabled or disabled the button. The parent component fetches the current user asynchronously, which should give the component access to the user model and the users credits.
CHILD COMPONENT:
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import SurveyList from './surveys/SurveyList';
class Dashboard extends Component {
render() {
console.log(this.props);
return (
<div>
<SurveyList />
<div className="fixed-action-btn">
{this.props.auth.credits &&
<Link to="/surveys/new" className="btn-floating btn-large red">
<i className="material-icons">add</i>
</Link>
}
<button className="btn-floating btn-large disabled red">
<i className="material-icons">add</i>
</button>
</div>
</div>
);
}
};
function mapStateToProps(state) {
return {
auth: state.auth
}
}
export default connect(mapStateToProps)(Dashboard);
PARENT COMPONENT:
import React, { Component } from 'react';
import { BrowserRouter, Route } from 'react-router-dom';
import Header from './Header';
import { connect } from 'react-redux';
import * as actions from '../actions';
import Landing from './Landing';
import Dashboard from './Dashboard';
import NewList from './lists/NewList';
class App extends Component {
componentDidMount() {
this.props.fetchUser();
}
render() {
console.log(this.props);
return (
<div className="container">
<BrowserRouter>
<div>
<Header />
<Route exact path='/' component={Landing} />
<Route exact path='/surveys' component={Dashboard} />
<Route path='/surveys/new' component={NewList} />
</div>
</BrowserRouter>
</div>
);
}
};
export default connect(null, actions)(App);
ACTION:
export const fetchUser = () => async dispatch => {
const res = await axios.get('/api/currentUser')
dispatch({ type: FETCH_USER, payload: res.data});
};
Add an additional check this.props.auth && this.props.auth.credits &&...

Clickable routing without link tag in react js

I want to navigate to another page when that component is clicked so i used to do that easily with Link tag but i want to navigate without link tag . is there any routing concepts rather that this Link tag . can someone clarify me pls .Here i attached my code ,
// Libraries
import React, { Component, Button, PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Link } from 'react-router-dom'
import {Row} from './dataTables/Row';
class Customers extends Component {
constructor(props) {
super(props);
}
componentWillMount() {
this.props.customersActions.fetchCustomers();
}
render() {
return (
<div className="customer-container">
<div className="body-container">
<div className="row-scroll">
{this.props.customersData.customers.filter(function(customer, index) {
if(index != 0) return true;
else return false;
}).map(customer =>
<Link to={'/customer/'+ customer.customer_id} key={customer.customer_id} className="line-removal">
<Row customer={customer} />
</Link> // what are all the other options instead of Link ???
)
}
</div>
</div>
</div>
);
}
}
function mapStateToProps(state, ownProps) {
return { customersData: state.customers };
}
export default connect(
})
)(Customers);
above is my code , can someone pls help me out from this.
You can use history.push() and standard react onClick to build the same behaviour like <Link /> provides.
Working demo (click on "Go to About" button): https://codesandbox.io/s/ER23MMvL0
Home.js
import React from 'react';
export default ({ history }) => {
const handleClick = () => {
history.push('/about');
};
return (
<div>
<h1>Home</h1>
<button onClick={handleClick}>Go to About</button>
</div>
);
};
index.js
import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import Home from './Home';
import About from './About';
const styles = {
fontFamily: 'sans-serif',
textAlign: 'center',
};
const App = () => (
<Router>
<div style={styles}>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
</ul>
<hr/>
<Route exact path="/" component={Home}/>
<Route path="/about" component={About}/>
</div>
</Router>
);
render(<App />, document.getElementById('root'));
You can use useNavigate() in Router v6.
import { useNavigate } from "react-router-dom";
const Home = () => {
const navigate = useNavigate();
<button onCLick={() => navigate("/about")}>Click me!</button>;
};

Resources