I try page isfocused work this method.this is working and go to getuserform method.But Axios
does not request again.I can't see any response or exception.I get old data again.
useEffect(() => {
dispatch(getUserForm(id))
}, [id, isFocused])
export const getUserForm = (userId) => {
return dispatch => {
axios.get(`${APIURL}/Form/${userId}`)
.then(response => {
dispatch({
type: 'GET_USER_FORM',
userForm: response.data,
})
})
.catch(err => console.error)
}
}
Related
I have this existing working VueJs code
const actions = {
retrieveStatus({ rootState, commit, dispatch }) {
return Axios
.get('/abc/GetStatus', {
params: {
draftId: rootState.eform.Id
}
})
.then(response => {
commit('SET_STATUS', response.data.statusCode);
return response.data;
})
.catch(err => {
throw new Error('Errors');
})
},
I don't see anywhere it uses dispatch but it exists there.
I am trying to pull data from MongoDB to populate some timers in this app I'm building. However, I can't seem to send my response to the front end with Axios. Here is my route on the backend:
const express = require('express');
const router = express.Router();
const TimerModel = require('../models/Timer');
router.get('/', async (req, res) => {
try {
const timers = await TimerModel.find({});
console.log('Succesful get req', timers);
res.send(timers);
} catch (err) {
console.log(err.message);
res.status(500).send('Server Error');
}
});
module.exports = router;
My console.log in the try statement prints the correct data but I'm having issues with sending it to the front end. Here is the component:
import React, { useState, useEffect } from 'react';
import Timer from '../Timer/Timer';
import axios from 'axios';
import './Wrapper.css';
function Wrapper() {
//State effects
useEffect(() => {
axios
.get('/')
.then((res) => {
console.log(res);
console.log(res.data);
})
.catch((err) => {
console.log(err);
});
});
const handleChange = (event) => {
setTitle(event.target.value);
};
const addTimer = () => {
const timer = <Timer title={title} key={timers.length} />;
let allTimers = timers.slice();
allTimers.push(timer);
setTimers(allTimers);
setTitle('');
};
return (
//JSX Code
);
}
export default Wrapper;
In the axios call I make, I get this weird object when I run console.log(res) and I get my index.html for the res.data. Why don't I have access to the timers object I made with my backend request? Isn't it being sent when I run the command res.send(timers) in my route?
You need to add your API url in axios request. Currently, axios is taking url of your React website that is why your response have index.html file of React website.
useEffect(() => {
axios
.get('api_url/')
.then((res) => {
console.log(res);
console.log(res.data);
})
.catch((err) => {
console.log(err);
});
});
You can save the result in a state like
`````````````
`````````````
const [time, setTimer] = useState(null)
useEffect(() => {
axios.get('/').then(res => setTimer(res.data)
}, [])
`````````````
`````````````
and then use time vairable where you want
So what I want to do is throw my APIs in one file. This way it makes my app way more reusable.
Problem is that I don't know how to do what I'm doing.
My parent file holds all the Hooks I need for data.
I am trying to get the Parent file to call the API, run the call to get the data, then that data then calls back and sets the hook in the parent.
Parent File
import { handleDepartments } from './API/API';
export default function App() {
const [departments, setDepartments] = useState([]);
useEffect(() => {
handleDepartments;
}, []);
The API file..
export const handleDepartments = async () => {
console.log('getting Departments');
const data = await axios
.get(`URI`, {
headers: {
Authorization: 'API_KEY',
Accept: 'application/json',
},
})
.then((response) => {
setDepartments(response.data.departments);
})
.catch((err) => {
console.log(err);
});
};
You're on the right track but its not a great idea to pass down a setState function into the api to update the parent component. Instead, its better practice to make the api call only return data, then the parent can decide how to deal with it.
Api:
export const handleDepartmentsApi = async () => {
await axios
.get(`URI`, {
headers: {
Authorization: 'API_KEY',
Accept: 'application/json',
},
})
.then((response) => {
return data;
})
.catch((err) => {
return err;
});
};
Parent:
export default function App() {
const [departments, setDepartments] = useState([]);
const getDepartments = async () => {
try {
const response = await handleDepartmentsApi();
setDepartments(response.data.departments)
} catch (err) {
//handle error or do whatever
}
}
useEffect(() => {
getDepartments();
}, []);
return (<></>)
}
I'm trying to add a props inside a componentDidMount from redux.
If i try to log in in to my app with componentDidUpdate i'm able to see the data loaded, but if i close the app and after i try to re open it, i can't see the data.
class Profile extends Component {
constructor(props) {
super(props);
this.state = {
results: []
};
}
componentDidUpdate = () => {
this.getMyWeather();
};
getMyWeather = () => {
const {
getUser: { userDetails }
} = this.props;
axios
.get(
settings.host +
'my_api_url',
{
headers: { Authorization: 'Token ' + userDetails.token },
}
)
.then(({ data }) => {
this.setState({
results: data.results
});
})
.catch(error => alert(error));
};
render() {
return (
<View style={styles.container}>
{this.state.results &&
this.state.results.map((data, index) => (
<Text key={index}>{data.title}</Text>
))}
</View>
);
}
}
let mapStateToProps;
mapStateToProps = state => ({
getUser: state.userReducer.getUser
});
let mapDispatchToProps;
mapDispatchToProps = dispatch => ({
dispatch
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(Profile);
How i can fetch the data also after closing and re-open the app?
Try this way
async componentDidMount() {
// GET request using axios with async/await
const {userDetails} = this.props.getUser; <-- Try this way -->
const data = await this.getMyWeather(userDetails);
this.setState({
results: data
});
}
getMyWeather = async (userDetails) => {
await axios
.get(
settings.host +
'my_api_url',
{
headers: { Authorization: 'Token ' + userDetails.token },
}
)
.then(({ data }) => {
return data.results;
})
.catch(error => alert(error));
};
Why to save to token in your redux in the first place?
personally I save it in local storage it's easy.
as you know redux is a state management of react this is mean when the you close the website the data store in redux die and because of this I think you should save in the local storage so you can get access to it really easy.
If you save the JWT in the DB you just need in the useEffect in the app.js call the action in redux that extract the JWT and save it
I have been trying to get a variable from AsyncStorage and then put it into an Axios get request. The problem is that the variable is not updating to the data that is retrieved from AsyncStorage. How do I make it do that?
Here is my code:
const [sku, setSku] = useState('')
const STORAGE_KEY_SKU = '#save_sku'
const readSku = async () => {
try {
const selectedSku = await AsyncStorage.getItem(STORAGE_KEY_SKU)
if (selectedSku !== null) {
setSku(selectedSku)
}
} catch (e) {
alert('Failed to fetch the data from storage')
}
}
useEffect(() => {
readSku()
}, []);
useEffect(() => {
Axios.get(`https://api.vexdb.io/v1/get_matches?sku=${sku}`)
.then(({ data }) => {
//console.log("defaultApp -> data", data)
setData(data.result)
})
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, []);
Im trying to put get the sku variable from the state from AsyncStorage, but the ${sku} in the axios get request link is not working, the sku is blank in that statement.
Please help, thanks!
useFocusEffect(() => {
readSku()
}, []);
const STORAGE_KEY_SKU = '#save_sku'
// to get the session username from localstorage
const readSku = async () => {
try {
const selectedSku = await AsyncStorage.getItem(STORAGE_KEY_SKU)
if (selectedSku !== null) {
setSku(selectedSku)
}
} catch (e) {
console.log(e);
}
}
const setSku = async (selectedSku) => {
Axios.get(`https://api.vexdb.io/v1/get_matches?sku=${selectedSku}`)
.then(({ data }) => {
//console.log("defaultApp -> data", data)
setData(data.result)
})
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}