I am very new in React-redux-hooks. My objective is to bring the data from inputView.js into temperatureView.js when I click button.
Here is some of my code,
I initialize useSelector
and useDispatch
inside inputView.js
const temperatureSelector=useSelector(state=>state.temperatureInfo)
const dispatch = useDispatch();
...
const handleClick = (e) => {
e.preventDefault();
dispatch(getTemperature());
history.push({
pathname: '/temperatureView',
state: { params: temperatureSelector }
})
}
When I log inside temperatureView.js, it gives nothing. Am I using the useSelector wrongly? or maybe useDispatch? Or should I dispatch inside useEffect?
How to do this?
EDIT
actions/index.js
export const getTemperature = (city) => {
return async function(dispatch) {
await fetch("myhttp").then(res => {
return res.json();
}).then(resJOSN => {
dispatch({type: "GET_TEMPERATURE", payload: resJOSN})
}).catch(err => {
console.log(err);
})
}
}
reducers/index.js
import { combineReducers } from 'redux';
const temperatureinfo = (state = {
temperatureinfo:{}
}, action) => {
if(action.type === "GET_TEMPERATURE") {
state = {...state, temperatureInfo:action.payload}
}
return state
}
const reducers = combineReducers ({
temperatureInfo:temperatureinfo,
})
export default reducers;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './view/App';
import reportWebVitals from './reportWebVitals';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import reducers from './reducers';
import thunk from 'redux-thunk';
ReactDOM.render(
<Provider store={createStore(reducers, applyMiddleware(thunk))}><App /></Provider>,
document.getElementById('root')
);
reportWebVitals();
App.js
import TemperatureView from './TemperatureView';
import InputView from './InputView';
function App(props) {
return (
<div>
<BrowserRouter>
<Route path="/" exact component={InputView} />
<Route path="/temperatureView" component={TemperatureView}/>
</BrowserRouter>
</div>
);
}
export default App;
InputView.js
import React, {useEffect} from 'react';
import { makeStyles } from '@material-ui/core/styles';
import InputLabel from '@material-ui/core/InputLabel';
import MenuItem from '@material-ui/core/MenuItem';
import Select from '@material-ui/core/Select';
import FormControl from '@material-ui/core/FormControl';
import Input from '@material-ui/core/Input';
import Button from '@material-ui/core/Button';
import { useHistory } from "react-router-dom";
import { useSelector, useDispatch } from 'react-redux';
import { getTemperature } from '../actions';
const useStyles = makeStyles((theme) => ({
root: {
'& > *': {
margin: theme.spacing(1),
},
},
}));
function InputView(props) {
const history = useHistory();
const classes = useStyles();
const City = [
{"id": "YG", "name": 'Yangon'},
{"id": "NY", "name": 'New York'}
];
const [state, setState] = React.useState({
apiKey: '123',
cityName: 'NY'
});
const temperatureSelector=useSelector(state=>state.temperatureInfo)
const dispatch = useDispatch();
const handleChange = (event) => {
const name = event.target.name;
setState({
...state,
[name]: event.target.value,
});
};
const handleChange1 = (event) => {
const name = event.target.name;
setState({
...state,
[name]: event.target.value,
});
};
const handleClick = (e) => {
e.preventDefault();
dispatch(getTemperature());
history.push({
pathname: '/temperatureView',
state: { params: temperatureSelector }
})
}
useEffect(()=>{
console.log('mounted');
return () => console.log('unmounting...');
},[]
);
return (
<div style={{display: "flex", height:"100vh", alignItems:"center", justifyContent:"center" }}>
<form className={classes.root} noValidate autoComplete="off">
<div style={{marginTop:"40px", marginBottom:"40px"}}>
<FormControl>
<InputLabel htmlFor="input-form" style={{color:"red"}}>Your API Key</InputLabel>
<Input id="input-form" value={state.apiKey} name="apiKey" onChange={handleChange} style={{width:"300px"}} />
</FormControl>
</div>
<div style={{marginTop:"40px", marginBottom:"40px"}}>
<FormControl className={classes.formControl}>
<InputLabel shrink id="button-file" style={{color:"red"}}>
City Name
</InputLabel>
<Select
labelId="button-file"
id="button-file"
value = {state.cityName}
displayEmpty
name="cityName"
onChange={handleChange1}
style={{width:"300px"}}
>
<MenuItem key={City[0].id} value={City[0].id}>
{City[0].name}
</MenuItem>
<MenuItem key={City[1].id} value={City[1].id}>
{City[1].name}
</MenuItem>
</Select>
</FormControl>
</div>
<div style={{marginTop:"100px", marginBottom:"100px"}}>
<Button type="submit" htmlFor="button-file" variant="contained" color="secondary" fullWidth={true} onClick={handleClick} >Submit</Button>
</div>
</form>
</div>
);
}
export default InputView;
TemperatureView.js
import React from 'react';
import Typography from '@material-ui/core/Typography';
import TextField from '@material-ui/core/TextField';
function TemperatureView(props) {
return <div style={{marginTop: "80px", marginLeft: "40px"}}>
<Typography color="error" >
Celcius
</Typography>
<TextField
id="celcius"
defaultValue="23.5"
InputProps={{
readOnly: true,
}}
/>
<Typography color="error" >
Fahrenheit
</Typography>
<TextField
id="fahrenheit"
defaultValue="2234"
InputProps={{
readOnly: true,
}}
/>
</div>
}
export default TemperatureView;
temperatureSelector
value has updated, storing whatever the current value is in route state. - Drew Reese