React this.state is null - reactjs

I try to do weather app in react, but when I add ${this.state.latitude} in my const API I replaced null.
But when I try display this.state.latitude in render() I have a value.
What is wrong?
export class TodayWeather extends React.Component {
constructor(props) {
super(props);
this.state = {
latitude: "",
longitude: "",
};
}
getMyLocation =() => {
const location = navigator.geolocation;
if (location) {
location.getCurrentPosition((position) => {
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
})
},)}
};
getWeather = () => {
this.getMyLocation();
const API = `http://api.openweathermap.org/data/2.5/forecast?lat=${this.state.latitude}&lon=139&appid=${apiKey}`;
fetch(API)
.then(response => {
if (response.ok) {
return response
}
throw Error("")
})
.then(response => response.json())
.then(data => {
const time = new Date().toLocaleString();
this.setState({
})
})})
};
componentDidMount() {
this.getWeather();
}
render(){
return (
<div className="App">
<Result className="result" weather={this.state}/>
<p> {this.state.latitude} </p>
</div>
);
}
}

The expected order of execution is:
this.getMyLocation() which sets the latitude and longitude to state.
this.getWeather() which uses the state variable to make a xhr request (which is again async).
this.setState is also asynchronous. So by the time the state variables are set, this.getWeather() already starts executing, so it comes back null and the fetch request fails. So when the state variable is set, it triggers a rerender, which is why it does come in the render.
The solution to this is using a callback in the setState. I have made some minor modifications.
I called this.getMyLocation() on componentDidMount:
componentDidMount() {
this.getMyLocation();
}
In which I make use of the callback and invoke the modified this.getWeather:
this.setState(
{
latitude: position.coords.latitude,
longitude: position.coords.longitude
},
this.getWeather
);
Where it no longer invokes this.getMyLocation() at its start.
Besides this, one obvious flaw is that you are not passing anything to the setState after the fetch is done, presumably the json data you obtain.
.then((data) => {
const time = new Date().toLocaleString();
this.setState({
// Something needs to come here, possibly:
data
});
});
The full code:
export default class TodayWeather extends Component {
constructor(props) {
super(props);
this.state = {
latitude: '',
longitude: ''
};
}
getMyLocation = () => {
const location = navigator.geolocation;
if (location) {
location.getCurrentPosition((position) => {
this.setState(
{
latitude: position.coords.latitude,
longitude: position.coords.longitude
},
this.getWeather
);
});
}
};
getWeather = () => {
const API = `http://api.openweathermap.org/data/2.5/forecast?lat=${
this.state.latitude
}&lon=139&appid=${apiKey}`;
fetch(API)
.then((response) => {
if (response.ok) {
return response;
}
throw Error('');
})
.then((response) => response.json())
.then((data) => {
const time = new Date().toLocaleString();
this.setState({
// Something needs to come here
data
});
});
};
componentDidMount() {
this.getMyLocation();
}
render() {
return (
<div className="App">
<Result className="result" weather={this.state} />
<p> {this.state.latitude} </p>
</div>
);
}
}

try this.. but the code looks very messy
export default class TodayWeather extends React.Component {
constructor(props) {
super(props);
this.state = {
latitude: '',
longitude: ''
};
}
getMyLocation = (getData) => {
const location = navigator.geolocation;
if (location) {
location.getCurrentPosition((position) => {
getData(position);
});
}
};
getWeather = () => {
const getData = (position) => {
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude
});
const API = `http://api.openweathermap.org/data/2.5/forecast?lat=${
position.coords.latitude
}&lon=139&appid=${apiKey}`;
fetch(API)
.then((response) => {
if (response.ok) {
return response;
}
throw Error('');
})
.then((response) => response.json())
.then((data) => {
const time = new Date().toLocaleString();
this.setState({ time });
});
};
this.getMyLocation(getData);
};
componentDidMount() {
this.getWeather();
}
render() {
return (
<div className="App">
<Result className="result" weather={this.state} />
<p> {this.state.latitude} </p>
</div>
);
}
}

Related

How to pass data from Component to form submit in ReactJS?

I have created Dropdown which extends Component. In this I am fetching muliple dropdown values an storing it in const data. I want pass this data from Dropdown Component to another Component in the form of function.
Any help would be really great as I am new to React and facing bit challenge.
export class CascadingDropdown extends Component {
constructor(props) {
super(props)
this.state = {
...
dropdown_data: []
}
}
componentDidMount() {
axios.get('/api/fetchCategory').then(response => {
this.setState({
CategoryData: response.data
});
});
}
ChangeSubCategory = (e) => {
this.setState({
category_id: e.target.value
});
axios.get('/api/fetchSubCategory?category_id=' + e.target.value).then(response => {
// console.log(response.data);
this.setState({
SubCategoryData: response.data,
});
});
}
ChangeSubject = (e) => {
this.setState({
sub_category_id: e.target.value
});
axios.get('/api/fetchSubjects?sub_category_id=' + e.target.value).then(response => {
// console.log(response.data);
this.setState({
subject: response.data
});
});
}
storeData = (e) => {
this.setState({
subject_id: e.target.value
});
}
render() {
const dropdown_data = {
category_id: this.state.category_id,
sub_category_id: this.state.sub_category_id,
subject_id: this.state.subject_id
}
console.log(dropdown_data)
return (
<div className ="row">
. . .
</div>
)
}
}
export default CascadingDropdown
The value from dropdown_data should be passed to a function and below is the code that I have tried.
function CreateTicket() {
const [ticketInput, setTicketInput] = useState({
category_id: '',
sub_category_id: '',
subject_id: '',
other_subject: '',
file: '',
auto_message: '',
});
const handleTicketInput = (e) => {
e.persist();
setTicketInput({...ticketInput, [e.target.name]: e.target.value })
}
const submitTicket = (e) => {
e.preventDefault();
const data = {
...
}
axios.post(`/api/store-ticket`, data).then(res => {
console.log(res.data);
. . .
})
}
return (
<div className ="container">
<form onSubmit ={handleSubmit}>
<input id="emp_name" type="text" name="employee_name" className ="form-control" disabled = "disabled" onChange = {handleTicketInput} value = {empname} />
<CascadingDropdown />
<input id="form_other_subject" type="text" name="other_subject" disabled = "disabled" className ="form-control" value = {ticketInput.other_subject} onChange = {handleTicketInput} />
</form>
</div>
)
}
export default CreateTicket;
This is what i can do for nested state,
and update states, i have used single json object dropdown_data and passed down to children, its getting complex to update state of it but easy to prop down the children,
Soution 1 (OLD):
export class CascadingDropdown extends Component {
constructor(props) {
super(props)
this.state = {
dropdown_data: {
subject_id, category_id, sub_category_id
},
CategoryData,
SubCategoryData,
subject
}
}
this.ChangeSubCategory = this.ChangeSubCategory.bind(this);
this.ChangeSubject = this.ChangeSubject.bind(this);
this.storeData = this.storeData.bind(this);
componentDidMount() {
axios.get('/api/fetchCategory').then(response => {
this.setState({
...this.state,
CategoryData: response.data
});
});
}
ChangeSubCategory = (e) => {
this.setState({
...this.state,
dropdown_data: {
...this.state.dropdown_data,
category_id: e.target.value
}
});
axios.get('/api/fetchSubCategory?category_id=' + e.target.value).then(response => {
// console.log(response.data);
this.setState({
...this.state,
SubCategoryData: response.data,
});
});
}
ChangeSubject = (e) => {
this.setState({
...this.state,
dropdown_data: {
...this.state.dropdown_data,
sub_category_id: e.target.value
}
});
axios.get('/api/fetchSubjects?sub_category_id=' + e.target.value).then(response => {
// console.log(response.data);
this.setState({
...this.state,
subject: response.data
});
});
}
storeData = (e) => {
this.setState({
...this.state,
dropdown_data: {
...this.state.dropdown_data,
subject_id: e.target.value
}
});
}
render() {
console.log(this.state.dropdown_data)
return (
<div className ="row">
<CreateTicket dropdown_data={this.state.dropdown_data}/>
</div>
)
}
}
export default CascadingDropdown
you can even pass function callbacks too,
<CreateTicket dropdown_data={this.state.dropdown_data} ChangeSubCategory={ChangeSubCategory} ChangeSubject={ChangeSubject} storeData={storeData}/
this is how you can get your parent state down into functional componenet
function CreateTicket(props) {
const [dropdown_data, setDropdown_data] = useState(props.dropdown_data); // use hooks now
//const dropdown_data = this.props.dropdown_data;
}
my new edited answer as per your new question is as follows,
Soution 2 (NEW):
export class CascadingDropdown extends Component {
constructor(props) {
super(props)
this.state = {
dropdown_data: {
subject_id:this.props.subject_id, category_id:this.props.category_id, sub_category_id:this.props.sub_category_id
},
CategoryData,
SubCategoryData,
subject
}
}
// this.ChangeSubCategory = this.ChangeSubCategory.bind(this);
// this.ChangeSubject = this.ChangeSubject.bind(this);
// this.storeData = this.storeData.bind(this);
componentDidMount() {
axios.get('/api/fetchCategory').then(response => {
this.setState({
...this.state,
CategoryData: response.data
});
});
}
ChangeSubCategory = (e) => {
this.props.ChangeSubCategory(e.target.value)
this.setState({
...this.state,
dropdown_data: {
...this.state.dropdown_data,
category_id: e.target.value
}
});
axios.get('/api/fetchSubCategory?category_id=' + e.target.value).then(response => {
// console.log(response.data);
this.setState({
...this.state,
SubCategoryData: response.data,
});
});
}
ChangeSubject = (e) => {
this.props.ChangeSubject(e.target.value);
this.setState({
...this.state,
dropdown_data: {
...this.state.dropdown_data,
sub_category_id: e.target.value
}
});
axios.get('/api/fetchSubjects?sub_category_id=' + e.target.value).then(response => {
// console.log(response.data);
this.setState({
...this.state,
subject: response.data
});
});
}
storeData = (e) => {
this.props.storeData(e.target.value);
this.setState({
...this.state,
dropdown_data: {
...this.state.dropdown_data,
subject_id: e.target.value
}
});
}
render() {
console.log(this.state.dropdown_data)
return (
<div className ="row">
<CreateTicket />
</div>
)
}
}
export default CascadingDropdown
and its parent function is,
function CreateTicket(props) {
const [dropdown_data, setDropdown_data] = useState({
subject_id:"", category_id:"", sub_category_id:""
}); // use hooks now
ChangeSubCategory=(category_id)=>{
setDropdown_data({...dropdown_data,category_id})
}
ChangeSubject=(sub_category_id)=>{
setDropdown_data({...dropdown_data,sub_category_id})
}
storeData=(subject_id)=>{
setDropdown_data({...dropdown_data,subject_id})
}
return (
<div className ="container">
<form onSubmit ={handleSubmit}>
<input id="emp_name" type="text" name="employee_name" className ="form-control" disabled = "disabled" onChange = {handleTicketInput} value = {empname} />
<CascadingDropdown dropdown_data={dropdown_data} ChangeSubCategory={ChangeSubCategory} ChangeSubject={ChangeSubject} storeData={storeData}/>
<input id="form_other_subject" type="text" name="other_subject" disabled = "disabled" className ="form-control" value = {ticketInput.other_subject} onChange = {handleTicketInput} />
</form>
</div>
)
}
i hope this will work now,

Why can't I setState the data I've successfully in React?

So I'm new to React, and having trouble fetching API. I've successfully fetched data object(I've checked it with console.log(), but somehow cannot setState it. Please see the code below. It's my full code.
import React, { Component } from 'react';
import EachCake from './EachCake';
class Cake extends Component {
constructor(props){
super(props);
this.state = {
}
}
componentDidMount() {
this._fetchApiEachCake();
}
_renderEachCake = () => {
return <EachCake
image={this.cake_object.image}
source={this.cake_object.source}
body={this.cake_object.body}
/>
}
_fetchApiEachCake = () => {
return fetch("http://127.0.0.1:8000/api/cake/3")
.then((response) => response.json())
.then(data => console.log(data))
.then(data => this.setState({cake_object : data}))
// .catch((err) => console.log(err))
}
render() {
return (
<div>
{this.state.cake_object ? this._renderEachCake() : "Loading this cake"}
</div>
)
}
}
export default Cake
For some reason, all I get on the screen is "Loading this cake". What do you think is the problem?
import React, { Component } from 'react';
import EachCake from './EachCake';
class Cake extends Component {
constructor(props){
super(props);
this.state = {
// 🔥 state initialization is optional also, useful for default values
}
}
componentDidMount() {
this._fetchApiEachCake();
}
_renderEachCake = () => {
return (
<EachCake
image={this.state.cake_object.image} // 🌟🌟
source={this.state.cake_object.source}
body={this.state.cake_object.body}
/>
)
}
_fetchApiEachCake = () => {
// 🔥 you can also remove return here
return fetch("http://127.0.0.1:8000/api/cake/3")
.then((response) => response.json())
.then(data => console.log(data) || data) // 🌟
.then(data => this.setState({cake_object : data}))
// .catch((err) => console.log(err))
}
render() {
return (
<div>
{this.state.cake_object ? this._renderEachCake() : "Loading this cake"}
</div>
)
}
}
export default Cake
🌟🌟 must be grabbed from the state not directly from this reference.
🌟 console.log doesn't return anything, so you must return data yourself oق combine setState and logging step both in one step e.g.
.then(cake_object => console.log(cake_object) || this.setState({ cake_object }))
The then() method returns a Promise.
if you are trying to check if the data is loaded or not you should use the callback this.setstate({key: value}, () => {//do something})
you can use this to set a flag whether data has been loaded into state or not. and i also think that you should initialize that cake_object to null.
so after that your code would be like:
this.state = {
loaded: false,
cake_object: null
}
_fetchApiEachCake = () => {
return fetch("http://127.0.0.1:8000/api/cake/3")
.then((response) => response.json())
.then(data => console.log(data))
.then(data => this.setState({cake_object : data}, () => {
console.log(this.state.cake_object);
this.setState({loaded: true});
}))
// .catch((err) => console.log(err))
}
render() {
return (
<div>
{this.state.loaded ? this._renderEachCake() : "Loading this cake"}
</div>
)
}
2 changes :
1.
this.state = {
cake_object:null,
}
_fetchApiEachCake = () => {
return fetch("http://127.0.0.1:8000/api/cake/3")
.then((response) => response.json())
.then((data) => {
console.log(data)
this.setState({cake_object : data})
})
// .catch((err) => console.log(err))
}
Hopefully it works!

Warning: Can't perform a React state update on an unmounted component....componentWillUnmount method

I'm very new to React and React Native and I am getting this warning when I switch screens. Also, the console.log keeps repeating infinitely, how do I fix it?
class DecodeScreen extends Component {
state = {
data: this.props.navigation.getParam("data", "NO-QR"),
bookData: '',
bookFound: false
}
bookSearch = () => {
query = `https://librarydb-19b20.firebaseio.com/books/${this.state.data}.json`,
axios.get(query)
.then((response) => {
const data = response.data ? response.data : false
console.log(data)
if (data) {
this.setState({
bookData: data,
bookFound: true
})
}
}).catch((error) => {
this.setState({
bookFound: false
})
})
}
renderContent = () => {
if (this.state.bookFound) {
return(
<View>
<TextH5>{this.state.bookData.title}</TextH5>
<TextH5>{this.state.bookData.author}</TextH5>
<TextH5>{this.state.bookData.publisher}</TextH5>
<TextH5>{this.state.bookData.isbn}</TextH5>
</View>
)
}
else {
return <TextH5>beer not found</TextH5>
}
}
componentDidMount() {
this.bookSearch()
}
render() {
{this.bookSearch()}
return (
<Container>
<TextH5>{this.state.data}</TextH5>
{this.renderContent()}
</Container>
);
}}
export default DecodeScreen;
the console.log outputthe warning
You can try this approach to see if it fixes the problem.
isMounted = false;
class DecodeScreen extends Component {
state = {
data: this.props.navigation.getParam("data", "NO-QR"),
bookData: "",
bookFound: false,
};
bookSearch = () => {
this.isMounted = true;
(query = `https://librarydb-19b20.firebaseio.com/books/${this.state.data}.json`),
axios
.get(query)
.then((response) => {
const data = response.data ? response.data : false;
console.log(data);
if (data) {
if (this.isMounted) {
this.setState({
bookData: data,
bookFound: true,
});
}
}
})
.catch((error) => {
this.setState({
bookFound: false,
});
});
};
renderContent = () => {
if (this.state.bookFound) {
return (
<View>
<TextH5>{this.state.bookData.title}</TextH5>
<TextH5>{this.state.bookData.author}</TextH5>
<TextH5>{this.state.bookData.publisher}</TextH5>
<TextH5>{this.state.bookData.isbn}</TextH5>
</View>
);
} else {
return <TextH5>beer not found</TextH5>;
}
};
componentDidMount() {
this.isMounted = true;
this.bookSearch();
}
componentWillUnmount() {
this.isMounted = false;
}
render() {
{
this.bookSearch();
}
return (
<Container>
<TextH5>{this.state.data}</TextH5>
{this.renderContent()}
</Container>
);
}
}
export default DecodeScreen;
You have to use componentDidMount method to do api call
componentDidMount() {
this.bookSearch()
}
Read about react life cycle method

how to clear the input value after setting the state in react?

I am making a todo app in react and after taking input from the user on submit i am making a post request to update in the database and then updating the state. and then i am trying to clear the input field using
e.target.value = "". But this is not working. Iam fairly new to JS and React. can some one point me what i am doing wrong here.
class TodoApp extends Component {
constructor(props) {
super(props);
this.state = {
todos: [],
};`enter code here
this.handleTodos = this.handleTodos.bind(this);
this.handleLogout = this.handleLogout.bind(this);
this.removeTodo = this.removeTodo.bind(this);
};
componentDidMount() {
const authStr = 'Bearer ' + getJWTToken();
axios.get('/tasks', {
'headers': {
'Authorization': authStr
}
}).then(res => {
// console.log(res.data);
this.setState({
todos: res.data,
})
}).catch(err => {
console.log(err);
});
};
removeTodo = id => {
// console.log(id)
const authStr = 'Bearer ' + getJWTToken();
axios.delete('/tasks/' + id, {
'headers': {
'Authorization': authStr
}
}).then(res => {
// console.log(res.data);
let newTodos = [...this.state.todos];
newTodos = newTodos.filter(todo => {
return todo._id !== id;
});
//Update the State
this.setState({
todos: newTodos
});
}).catch(err => {
console.log(err);
});
};
handleTodos = e => {
e.preventDefault();
const authStr = 'Bearer ' + getJWTToken();
var todo = {
description: e.target.value
}
console.log(todo)
axios.post('/tasks', todo, {
'headers': {
'Authorization': authStr
}
}).then(res => {
// console.log(res.data);
this.setState({
todos: this.state.todos.concat(res.data)
})
}).catch(err => {
console.log(err)
});
e.target.value = "";
// console.log(todo);
};
handleLogout() {
localStorage.removeItem('jwtToken');
this.props.history.push("/");
}
render() {
const listLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 8 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 16 },
},
};
return (
<div className="container-fluid App">
<div className="todoContainer">
<Header
handleLogout={this.handleLogout}
/>
<h1 style={{ paddingTop: "10px" }}>TODO App</h1>
<Input
placeholder="What needs to be done?"
onPressEnter={this.handleTodos}
/>
<List
itemLayout="horizontal"
locale={{ emptyText: "No Todos" }}
dataSource={this.state.todos}
renderItem={item => (
<TodoItem
todo={item}
removeTodo={this.removeTodo}
/>
)}
/>
</div>
</div>
);
};
};
export default TodoApp;
The value of your input field should be bound to your state to properly control it. You can modify your state declaration like this:
this.state = {
todos: [],
whatToDo: ""
}
and bind your input field to your state like this:
<Input
placeholder="What needs to be done?"
onPressEnter={this.handleTodos}
value={this.state.whatToDo}
onChange={this.onInputChange} // will update the state on each change
/>
then create the onInputChange function:
onInputChange= (event, data) => {
this.setState({ whatToDo: data.value });
}
and lastly, change the line
e.target.value = "";
to
this.setState({ whatToDo: "" });
try this,
handleTodos = e => {
e.preventDefault();
const authStr = 'Bearer ' + getJWTToken();
var todo = {
description: e.target.value
}
console.log(todo)
axios.post('/tasks', todo, {
'headers': {
'Authorization': authStr
}
}).then(res => {
// console.log(res.data);
this.setState({
todos: this.state.todos.concat(res.data)
})
}).catch(err => {
console.log(err)
});
//RESET FIELD
e.target.reset()
};
You can use Refs to clear input text. This is the working solution.Also, follow this Reactjs link for more information.
class App extends React.Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
this.state = {
inputField: ""
};
}
keyHandler = event => {
if (event.key === "Enter") {
console.log(this.inputRef.current.value);
this.setState({ inputField: event.target.value });
this.inputRef.current.value = "";
}
};
render() {
return (
<div>
<input
type="text"
onKeyPress={this.keyHandler}
ref={this.inputRef}
/>
<p>{this.state.inputField}</p>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id='root'></div>
Allow me to tell you that this is not the react way of working generally speaking with inputs. I could also try to fix your error, but I prefer to bring you on the right path. Have a look at this doc page: https://reactjs.org/docs/forms.html
Particularly this stackoverflow answer: What are controlled components and uncontrolled components in ReactJS?
Using controlled components, to clear the input field, you just call setState emptying the content of a particular state variable. Please, have a look at the example I'm about to write:
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
}
handleChange = (event) => {
this.setState({value: event.target.value});
}
handleSubmit = (event) => {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
emptyInput = () => {
alert('Emptying input');
this.setState({ value: '' });
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
<button onClick={emptyInput}>Empty input</button>
</form>
);
}
}

How to increase axios speed?

Because I'm new to using axios so I usually have a trouble in using it. Specifically, I'm making a react-infinite-scroll feature now, but when I compare its speed with other site, my post(react-infinite-scroll feature) is gonna be shown slowly a little. Then I'm thinking this problem is caused by 2 reasons
1. I'm not using axios properly
2. There is a thing makes axios speed urgrade, but I'm not using it
Here's my code, please give me some advice to increase my http request speed.
Thank you for reading my question!
class MainPage extends Component {
constructor(props) {
super(props)
axios.get("http://127.0.0.1:8000/api/question")
.then(res => {
this.setState({
AnswerPostMultiList: res.data
})
}
)
.catch(err => {
console.log(err)
})
}
state = {
AnswerPostMultiList : []
}
componentDidMount() {
window.addEventListener("scroll", this.handleScroll);
}
componentWillUnmount() {
window.removeEventListener("scroll", this.handleScroll);
}
handleScroll = () => {
console.log("scroll is executing")
const { innerHeight } = window;
const { scrollHeight } = document.body;
const scrollTop =
(document.documentElement && document.documentElement.scrollTop) ||
document.body.scrollTop;
if (scrollHeight - innerHeight - scrollTop < 1000 && !this.props.isLoading["isLoading"]) {
this.props.onIsLoading() #To prevent this code from calling back continuously, change the value of this.props.isLoading["isLoading"] to false
axios.get("http://127.0.0.1:8000/api/question")
.then(res => {
this.setState({
AnswerPostMultiList: this.state.AnswerPostMultiList.concat(res.data)
})
this.props.onIsLoading() #change the value of this.props.isLoading["isLoading"] to true
}
)
.catch(err => {
console.log(err)
})
}
};
render() {
return(
<>
<PageHeader />
<div className="find_members">
{ this.state.AnswerPostMultiList.map((answerpost,index) => {
return <AnswerPostMulti question={answerpost.question_text} q_owner={answerpost.question_owner} answer={answerpost.answer_image} a_owner={answerpost.answer_owner} key={index} />
})
}
</div>
</>
)
}
}
const mapDispatchToProps = (dispatch) => ({
onIsLoading: () => {
dispatch(isLoadingActions.isLoading())
}
})
const mapStateToProps = state => ({
isLoading: state.isLoading
})
export default connect(mapStateToProps, mapDispatchToProps)(MainPage)
The best place to call a axios API calls is at componentDidMount(){}.
The Application loading process will be in this order skeleton->Initial rendering->later componentDidMount method is called. So here your app skeleton will be loaded and after that you can fetch data and use it to your app skeleton.
componentDidMount() {
axios.get("http://127.0.0.1:8000/api/question")
.then(res => {
this.setState({
AnswerPostMultiList: res.data
})
}
)
.catch(err => {
console.log(err)
});
}

Resources