How to send asynchronous state fetch to component? - javascript

I am currently working on a little app for fun. I ran into an issue with using axios and returning the response to my App component as updated state.
I then try to allow another component to use that piece of state, but I am not able to actually access the data. I can console.log(props) from within the List component, but I am not sure how to output the actual data as I am only able to output the promise results. I want to be able to output props.currentUser and have it be the googleId (using google Oauth2.0)..I am sure the solution is simple but, here is my code:
App.js ->
import React from 'react';
import helpers from '../helpers';
import List from './List';
class App extends React.Component{
state = {
currentUser: null
}
componentDidMount() {
this.setState(prevState => ({
currentUser: helpers.fetchUser()
}));
}
render() {
return (
<div>
<List currentUser={this.state.currentUser}/>
</div>
);
}
};
export default App;
helpers.js ->
import axios from 'axios';
var helpers = {
fetchUser: async () => {
const user = await axios.get('/api/current_user');
return user.data;
}
};
export default helpers;
List Component ->
import React from 'react';
const List = (props) => {
const renderContent = () => {
console.log(props);
return <li>{props.currentUser}</li>
}
renderContent();
return (
<div>
<h1>Grocery List</h1>
<ul>
</ul>
</div>
);
}
export default List;
Output ->
{currentUser: null}
{currentUser: Promise}
currentUser: Promise__proto__: Promise[[PromiseStatus]]: "resolved"

Because fetchUser is an async function, it returns a promise. Thus, in the App component, you have to call setState inside the .then of that promise, like so:
componentDidMount() {
helpers.fetchUser()
.then(data => {
this.setState(prevState => ({
currentUser: data
}));
});
}

Okay all you need to change is :
componentDidMount() {
this.setState(prevState => ({
currentUser: helpers.fetchUser()
}));
}
to
componentDidMount() {
helpers.fetchUser().then(data => {
this.setState(prevState => ({
currentUser: data
}));
})
}
WORKING DEMO (checkout the console)
NOTE : async await always returns the promise it just make
synchronousonus behaviour inside the async function but end ot the
function it will always returns the promise.

Related

Redux - How to get data from store and post it

Newbie to Redux here, I have tried to follow a couple tutorials and I am not clear of how Redux actually works. It was mentioned that the store of Redux is to store the state of the whole tree. I have created and used actions, reducers, and store for my program and it works.
The question is, how do I retrieve what is in the store? Lets say after updating my component, how can I retrieve the value inside the component and to post it?
How can I know what changed in my dropdown list and to retrieve it?
Full code in Sandbox here https://codesandbox.io/s/elated-goldberg-1pogb
store.js
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './RootReducer';
export default function configureStore() {
return createStore(
rootReducer,
applyMiddleware(thunk)
);
}
ProductsList.js
import React from "react";
import { connect } from "react-redux";
import { fetchProducts } from "./SimpleActions";
class ProductList extends React.Component {
constructor(props)
{
super(props);
this.state = {
selecteditems: '',
unitPrice: 0
}
}
componentDidMount() {
this.props.dispatch(fetchProducts());
}
componentDidUpdate(prevProps, prevState) {
if(prevState.selecteditems !== this.state.selecteditems)
{
this.setState((state, props) => ({
unitPrice: ((state.selecteditems * 1).toFixed(2))
}));
}
}
render() {
const { error, loading, products } = this.props;
if (error) {
return <div>Error! {error.message}</div>;
}
if (loading) {
return <div>Loading...</div>;
}
return (
<div>
<select
name="sel"
className="sel"
value={this.state.selecteditems}
onChange={(e) =>
this.setState({selecteditems: e.target.value})}
>
{products.map(item =>
<option key={item.productID} value={item.unitPrice}>
{item.itemName}
</option>
)}
</select>
<p>Unit Price: RM {this.state.unitPrice} </p>
</div>
);
}
}
const mapStateToProps = state => {
const products = state.productsReducer.items;
const loading = state.productsReducer.loading;
const error = state.productsReducer.error;
return {
products,
loading,
error,
}
};
export default connect(mapStateToProps)(ProductList);
SimpleAction.js
export function fetchProducts() {
return dispatch => {
dispatch(fetchProductsBegin());
return fetch('http://localhost:55959/api/products')
.then(handleErrors)
.then(res => res.json())
.then(results => {
dispatch(fetchProductsSuccess(results));
return results;
})
.catch(error => dispatch(fetchProductsFailure(error)));
};
}
function handleErrors(response) {
if(!response.ok) {
throw Error (response.statusText);
}
return response;
}
export const FETCHPRODUCTS_BEGIN = 'FETCHPRODUCTS_BEGIN';
export const FETCHPRODUCTS_SUCCESS = 'FETCHPRODUCTS_SUCCESS';
export const FETCHPRODUCTS_FAILURE = 'FETCHPRODCUTS_FAILURE';
export const fetchProductsBegin = () => ({
type: FETCHPRODUCTS_BEGIN
});
export const fetchProductsSuccess = products => ({
type: FETCHPRODUCTS_SUCCESS,
payload: {products}
});
export const fetchProductsFailure = error => ({
type: FETCHPRODUCTS_FAILURE,
payload: {error}
});
Thanks in advance!
You will need to pass your action handlers to connect function
connect(mapStateToProps,{actions})(ProductList).
how do I retrieve what is in the store? Lets say after updating my component, how can I retrieve the value inside the component and to post it?
if you want to see how is store change, you can add redux-logger to middleware to see that. when store change, it's likely a props change, you can handle this in function componentDidUpdate.
How can I know what changed in my dropdown list and to retrieve it?
values in dropdown is controlled by "const products = state.productsReducer.items;", productsReducer is controlled by actions you passed in dispatch like this: "this.props.dispatch(fetchProducts());".
I think you should add redux-logger to know more how to redux work, it show on console step by step. It will help you learn faster than you think :D
to retrieve it you forgot the selecteditems
const mapStateToProps = state => {
const products = state.productsReducer.items;
const loading = state.productsReducer.loading;
const error = state.productsReducer.error;
const selecteditems = state.prodcuts.selecteditems;
return {
products,
loading,
error,
selecteditems
};
};
To change it you should connect another function like
const mapDispatchToProps = dispatch => {
return {
onChangeDropdownSelection: (selected)=> dispatch(actions.setSelectedDropdown(selected))
}
}

How to Test Custom Hook with react testing library

I tried using react-hooks-testing-library but it dosn't seem how handle hooks that use useContext.
import React,{useContext} from 'react'
import {AuthContextData} from '../../AuthContext/AuthContext'
const useAuthContext = () => {
const {authState} = useContext(AuthContextData)
const {isAuth,token,userId,userData} = authState
return {isAuth,token,userId,userData}
}
export default useAuthContext
You have to wrap your hook in a context provider:
let authContext
renderHook(() => (authContext = useAuthContext()), {
wrapper: ({ children }) => (
<AuthContextData.Provider value={/* Your value */}>
{children}
<AuthContextData.Provider>
)
})
Let's say you have a component where you call the useContext(context) hook to get a key isLoading that should be false or true.
If you want to test useContext in a component you could test it as follow:
const context = jest.spyOn(React, 'useContext');
if each test in the same file need to have different context values, then inside your test, you can mock the implementation like this:
context.mockImplementationOnce(() => {
return { isLoading: false };
});
or outside the tests for all tests to have same context:
context.mockImplementation(() => {
return { isLoading: false };
});
Hope it helps.

How to pass variable when dispatching fetch function in react component?

I have react-redux app which fetching data from my node server, each time i need to fetch something i have to create same action where i change value in fetch, here is questions: How i can pass a variable in order to avoid duplicate code in such situation?
export function fetchProducts() {
return dispatch => {
dispatch(fetchProductsBegin());
return fetch("/api/followers")
.then(handleErrors)
.then(res => res.json().then(console.log(res)))
.then(json => {
dispatch(fetchProductsSuccess(json));
return json;
})
.catch(error => dispatch(fetchProductsError(error)));
};
}
Then i call fetchProduct:
class ProductList extends React.Component {
componentDidMount() {
this.props.dispatch(fetchProducts());
}
I want to have a result that where i call fetchProducts and put a variable, then each time using same action.
You can use following:
// in component:
this.props.dispatch(fetchProducts(id));
// in function
export function fetchProducts(id) {
Moreover, you can use
class ProductList extends React.Component {
componentDidMount() {
this.props. fetch(id);
}
const mapDispatchToProps = (dispatch) => ({
fetch: (id) => dispatch(fetchProducts(id))
});
export default connect(null, mapDispatchToProps)(ProductList)
About your code struct, you should use Axios library to call API, use
promise for wait API call instead of dispatch fetchProductsBegin.
in this case, you can rewrite the code as below:
export function fetchProducts(id) {
return dispatch => {
dispatch(fetchProductsBegin(id));
return fetch(`/api/followers/${id}`)
//...
}
call function
componentDidMount() {
this.props.dispatch(fetchProducts(id));
}

React - Passing fetched data from API as props to components

Iam trying to understand and learn how to pass around data as props to other components to use. Iam trying to build a top-level hierarchy where the API Request is made in a class at top level and then the result is passed around to child components to be used as props and then in states.
The problem is that when i pass the result i get "Object Promise" in my child component. How do I access the data sent as props to child components?
As you can see in my App.js in my render() method that i created a component of the class API and pass the result from the fetchData() method as parameter to the component.
In my API.js class i used console.log to check the result but
the result i get from the logs are:
line 5: {dataObject: Promise}
line 10: undefined
App.js:
import API from './API';
class App extends Component {
componentDidMount(){
this.fetchData();
}
fetchData(){
const url = "https://randomuser.me/api/?results=50&nat=us,dk,fr,gb";
return fetch(url)
.then(response => response.json())
.then(parsedJSON => console.log(parsedJSON.results))
.catch(error => console.log(error));
}
render() {
return (
<div className="App">
<API dataObject={this.fetchData()}/>
</div>
);
}
}
export default App;
API.js
import React from 'react';
class API extends React.Component{
constructor(props){
console.log(props);
super(props);
this.state = {
dataObj:props.dataObject
};
console.log(this.state.dataObject)
}
render() {
return(
<p>""</p>
)
}
}
export default API;
Try changing App.js to this:
import API from './API';
class App extends Component {
componentDidMount(){
this.fetchData();
}
fetchData(){
const url = "https://randomuser.me/api/?results=50&nat=us,dk,fr,gb";
return fetch(url)
.then(response => response.json())
.then(parsedJSON => this.setState({results: parsedJSON.results}))
.catch(error => console.log(error));
}
render() {
return (
<div className="App">
<API dataObject={this.state.results}/>
</div>
);
}
}
export default App;
This makes sure you fetch the data in componentDidMount and it now uses state to store the data which then will be passed into your API component.
If anyone is looking for an answer using Hooks then this might help.
App.js
import API from './API';
function App(props) {
const [result, setResult] = React.useState({});
// similar to componentDidMount
React.useEffect(() => {
this.fetchData();
}, []);
fetchData() {
const url = "https://randomuser.me/api/?results=50&nat=us,dk,fr,gb";
fetch(url)
.then(response => setResult(response.json()))
.catch(error => console.log(error));
}
return (
<div className="App">
<API dataObject={result}/>
</div>
);
}
export default App;
API.js
import React from "react";
function API(props) {
const [result, setResult] = React.useState(props.dataObject);
React.useEffect(() => {
setResult(result);
}, [result]);
return <p>{result}</p>;
}
export default API;
Hope it helps! And let me know if anything is incorrect.
You should fetch data in componentDidMount and not in render. Fetching the data within render causes the API request to be repeated, every time the DOM is re-rendered by react.js.
After making the GET request to the API endpoint, first parse the data into a javascript object, then set the results to state using this.setState from within your component.
From there, you may pass the data held in state to child components as props in the render function.
For example:
const App = (props) =>
<ChildComponent />
class ChildComponent extends React.Component {
constructor(props){
super(props);
this.state = {
results: []
}
}
componentDidMount(){
fetch('/api/endpoint')
.then(res => res.json())
.then(results => this.setState({results})
}
render(){
return <GrandchildComponent {...this.state} />
}
}
const GrandchildComponent = (props) =>
<div>{props.results}</div>

Cannot access data request Axios, React-Redux

I am trying to make an API request using Axios in React-Redux environment. On the console everything seems to be fine, however if I try to access any of the data I either get undefined or empty array.
This is my component:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { discoverMovie } from '../actions'
//Home component
class Home extends Component {
//make request before the render method is invoked
componentWillMount(){
this.props.discoverMovie();
}
//render
render() {
console.log('movie res ',this.props.movies.movies.res);
console.log('movie ',this.props.movies);
return (
<div>
Home
movie
</div>
)
}
};
const mapStateToProps = (state) => {
return{
movies : state.movies
}
}
export default connect(mapStateToProps, { discoverMovie })(Home);
This is my action
import { DISCOVER_MOVIE } from '../constants';
import axios from 'axios';
//fetch movie
const fetchMovie = () => {
const url = 'https://api.themoviedb.org/3/discover/movie?year=2018&primary_release_year=2018&page=1&include_video=false&include_adult=false&sort_by=vote_average.desc&language=en-US&api_key=72049b7019c79f226fad8eec6e1ee889';
let result = {
res : [],
status : ''
};
//make a get request to get the movies
axios.get(url).
then((res) => {
result.res = res.data.results;
result.status = res.status;
return result;
});
//return the result after the request
return result;
}
//main action
const discoverMovie = () =>{
const result = fetchMovie();
//return the action
return {
type : DISCOVER_MOVIE,
payload : result
}
}
export default discoverMovie;
This is the reducer
import { DISCOVER_MOVIE } from '../constants';
//initial state
const initialState = {
movies : {},
query : '',
};
//export module
export default (state = initialState, actions) =>{
switch(actions.type){
case DISCOVER_MOVIE :
return {
...state,
movies : actions.payload
};
default :
return state;
}
}
this is the log that I get from the console
as you can see if I log the entire object I see all data, however if go deep and try to access the result I either get an undefined or an empty array and using redux-dev-tools I noticed that the state does not contain any value.
I read on internet including this portal similar issue but could not find any solution for my issue.
Solution
From official docs:
You may use a dedicated status field in your actions
Basically you need to dispatch action for each state to make an async action to work properly.
const searchQuery = () => {
return dispatch => {
dispatch({
type : 'START',
})
//make a get request to get the movies
axios.get(url)
.then((res) => {
dispatch({type : 'PASS', payload : res.data});
})
.catch((err) => {
dispatch({type : 'FAILED', payload : res.error});
});
}
With redux-thunk it's pretty simple to set up. You just have to make some changes to your store. Out the box, I'm pretty sure redux isn't the most friendly with async and that's why thunk is there.
import { ..., applyMiddleware } from "redux";
import thunk from "redux-thunk";
...
const store = createStore(reducer, applyMiddleware(thunk));
...
Then in your action you'll need to return dispatch which will handle your logic for your axios call.
const fetchMovie = () => {
return dispatch => {
const url = //Your url string here;
axios.get(url).then(res => {
dispatch(discoverMovie(res.data.results, res.status);
}).catch(err => {
//handle error if you want
});
};
};
export const discoverMovie = (results, status) => {
return {
type: DISCOVER_MOVIE,
payload: results,
status: status
};
};
Your reducer looks fine, though with the way my code is typed you'll have status separately. You can combine them into it's own object before returning in discoverMovie, if you need status with the results.
This is my first answer on stack so let me know if I can clarify anything better!

Categories

Resources