I am building an issue tracker app that is based on react/django. I am trying to pass projects, a state variable that is an array of project objects, to manageusers so that I can have access to the name of the project in manageusers. The reason behind this is so that I can use that project name to find the project associated with it, and assign users to the project. I am using a state object to pass projects to a link, but when I try to load the manageusers webpage it is stating that state is undefined. Keep in mind the projects data from the django backend is coming in fine, I am just trying to get that data onto manageusers.
Project
project.js
import { useState, useEffect } from "react";
import { Grid, TextField, Button, Typography } from "@material-ui/core";
import {
BrowserRouter as Router,
Link,
Route,
Switch,
} from 'react-router-dom';
const project = () => {
const [name, setName] = useState();
const [description, setDescription] = useState();
const [projects, setProjects] = useState([]);
const post = () => {
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json"},
body: JSON.stringify({
name: name,
description: description,
}),
};
fetch("/api/newProject",requestOptions)
.then((response) => response.json())
.then((data) =>{
})
}
useEffect(() => {
fetch("/api/manageprojects")
.then((response) => response.json())
.then((data) =>{
setProjects(data)
})
}, [])
return (
<div>
<body>
<form action="#" method="POST">
<TextField onChange={(e) => setName(e.target.value)}> </TextField>
<br>
</br>
<TextField onChange={(e) => setDescription(e.target.value)}> </TextField>
<br>
</br>
<Button onClick={() => post()}> Create New Project </Button>
</form>
</body>
<div>
{projects && projects.map(project => (
<Grid item xs={3}>
<Typography component="h5" variant="h5">
<h5> {project.name} </h5>
<h5> {project.description} </h5>
</Typography>
</Grid>
))}
</div>
<Link to={{
pathname: '/manageusers',
state: {
projects: projects
}
}}>Manage Users
</Link>
</div>
);
}
export default project;
Manage Users
a portion of manageusers.js
const Name = (props) => {
const {projects} = props.location.state;
console.log(projects.name);
}
return (
<div>
<Select
value={selectedValue}
options={roles}
onChange={handleChange}
isOptionDisabled={option => option.isDisabled}
/>
<div class="ex1">
{role && role.map(roles => (
<Grid item xs={3}>
<Typography component="h5" variant="h5">
<h5> {roles.username} </h5>
</Typography>
</Grid>
))}
</div>
<Name/>
</div>
Instead of using React Router link,
what you need is a global store, such as Redux or Mobx. That way you can update the state with relevant data and retrieve them on the new page.
If you need a workaround, you could use history.pushState()
Basically you can push to your location and with it a state.
And on the next page, which is MyComp in this case, you could use history.state to retrieve the pushed data.