My django api responds with the username if the user is authenticated and a not authenticated details msg if not authenticated
but i am unable to read the status code or console log or catch the 401 status code and res.status gives undefined msg
console img
how can i use http status to render depending on the code received .
export default class GetUser extends Component {.....}
componentDidMount(){
fetch("http://127.0.0.1:8000/app/ebooks/",
{ CSRF_TOKEN.....
},
})
.then(res => res.json())
.then(res => {
this.setState({data:[res]})
console.log(resp.status) --->UNDIFINED
})
.catch(err => console.log(err));
}
render() {
var x = this.state.data
return (
<pre>{JSON.stringify(x, null, 2) }</pre>
)
}
}
Move the console.log() up to the first then clause.
.then(response => {
console.log(response.status) --> 401
return response.json()
})
.then(data => {
this.setState({data:[data]})
})
.catch(err => console.log(err));
Related
I'm succesfully fetching the data from API but unable to display it on the page. I tried like this
<ListGroupItem>
Charting : {data.properties?.chart_status}
</ListGroupItem>
but not getting it on page.
const fetchData = async () => {
if (context.pnr === '') {
return alert("Enter your PNR!")
} else {
await Axios.get(url, {
headers: {
'X-RapidAPI-Key': 'c7f77319b7mshbf31f81334ba8c6p172803jsn8c0911e4683a',
'X-RapidAPI-Host': 'pnr-status-indian-railway.p.rapidapi.com'
}
})
.then(res => {
setData(res.data)
console.log("Response: ", res.data)
})
.catch(err => console.log(err))
}
setData('')
}
Attached is data base schema
I'm having a problem that seems to be due to an async call. I have an action that makes an API call and pushes to a Dashboard page. That API call also updates state.account.id based on the response it gives back:
const submitLogin = e => {
e.preventDefault();
props.loginAndGetAccount(credentials);
props.history.push('/protected');
e.target.reset();
}
loginAndGetAccount is coming from this action:
export const loginAndGetAccount = credentials => dispatch => {
dispatch({ type: GET_ACCOUNT_START })
axios
.post('https://foodtrucktrackr.herokuapp.com/api/auth/login/operators', credentials)
.then(res => {
console.log(res);
dispatch({ type: GET_ACCOUNT_SUCCESS, payload: res.data.id })
localStorage.setItem("token", res.data.token)
})
.catch(err => console.log(err));
}
On the Dashboard page, I have useEffect set up to make another API call dynamically based on the value held in state.account.id. However, it seems the first API call is pushing to the Dashboard page before the response comes back and updates state.account.id. Therefore, when the second API call is made there, it's passing state.account.id to that dynamic API call as undefined, which, of course, results in a failed call. How can I resolve this?
Here's what's happening:
const Dashboard = props => {
const [accountInfo, setAccountInfo] = useState({});
useEffect(() => {
console.log(props.accountId);
axiosWithAuth()
.get(`/operator/${props.accountId}`)
.then(res => {
console.log(res);
})
.catch(err => console.log(err));
}, [])
return (
<div>
<h1>This is the Dashboard component</h1>
</div>
)
}
const mapStateToProps = state => {
return {
accountId: state.account.id
}
}
export default connect(mapStateToProps, {})(Dashboard);
The root of the problem is that you are making a request here, but not
export const loginAndGetAccount = credentials => dispatch => {
dispatch({ type: GET_ACCOUNT_START })
axios
.post('https://foodtrucktrackr.herokuapp.com/api/auth/login/operators', credentials)
.then(res => {
console.log(res);
dispatch({ type: GET_ACCOUNT_SUCCESS, payload: res.data.id })
localStorage.setItem("token", res.data.token)
})
.catch(err => console.log(err));
}
waiting for it to complete here before you navigate to the next page
const submitLogin = e => {
e.preventDefault();
props.loginAndGetAccount(credentials);
props.history.push('/protected');
e.target.reset();
}
the quickest way to fix this is to returnt the promise from loginAndGetAccount and then props.history.push in the resolution of that promise...
like this:
export const loginAndGetAccount = credentials => dispatch => {
dispatch({ type: GET_ACCOUNT_START })
// return the promise here
return axios
.post('https://foodtrucktrackr.herokuapp.com/api/auth/login/operators', credentials)
.then(res => {
console.log(res);
dispatch({ type: GET_ACCOUNT_SUCCESS, payload: res.data.id })
localStorage.setItem("token", res.data.token)
})
.catch(err => console.log(err));
}
...
const submitLogin = e => {
e.preventDefault();
props.loginAndGetAccount(credentials)
.then(() => {
// so that you can push to history when it resolves (the request completes)
props.history.push('/protected');
e.target.reset();
}
.catch(e => {
// handle the error here with some hot logic
})
}
When I click on button app sends request to an API (dispatching signIn action).
A server sends error (dispatching signInFailure action).
But in my case dispatching signIn -> signInSuccess -> signInFailure.
Help me please.
UserService.js
return await axios.post(url, data)
.then(response => { return response.data; })
.catch(error => { throw error; });
actions.js
export const signInUser = (username, password) => dispatch => {
dispatch(signIn({ username, password }));
userService.signIn(username, password)
.then(dispatch(signInSuccess()))
.catch(error => dispatch(signInFailure(error)));
};
Solution
In UserService need to throw an error. And then it works fine in action.
Make a change in this function as given below:
export const signInUser = (username, password) => dispatch => {
dispatch(signIn({ username, password }));
userService.signIn(username, password)
.then((res) => dispatch(signInSuccess()))
.catch((error) => dispatch(signInFailure(error)));
};
Please use return in catch
return await axios.post(url, data)
.then(response => { return response.data; })
.catch(error => { return error; }); // Use return here
I think you should change it
.then(response => { return response.data; })
to
.then(response => { if(response.status === 200) return response.data; else throw new Error("error") })
I think it happen when api has response from server ( it isn't going to catch ).
let resultofapi is declared globally and I initialized it with the value I received from API. I want to display that value to my react js page (inside a table). When I print the value inside the API it returns me output {"similarity_score":0.9999999404}.but when I access it outside the API, it gives me value=undefine
pd.usage()
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
**pd.semantic(
pd
.semantic(textarea1, textarea2)//these are forms data
.then(response => {
console.log(response); //output={"similarity_score":0.670276463}
*resultofapi = response;* //output=resultofapi={"similarity_score":0.670276463}*
})**
.catch(error => {
console.log(error);
})
)
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
console.log(resultofapi)//output=undefined
Make a state object and setState it with the API Data. From that you can access it allover your class.
this.state = {
items: []
};
componentDidMount() {
fetch("https://url.url.com")
.then(res => res.json())
.then(
(result) => {
this.setState({
items: result.items
});
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
return (
<ul>
{items.map(item => (
<li key={item.name}>
{item.name} {item.price}
</li>
))}
</ul>
);
I'm using axios to send requests to my server. Now I wanted to apply redirects in my frontend(React) using the window.location.href property. But the axios request is not being sent. I also tried to carry out an axios request and reload the page and it doesn't work even then.
axios.post("/api/orders",params)
.then(res => {
console.log("Order Placed");
axios.delete("/api/cart/"+user_id)
.then(res => {
console.log("Cart Deleted");
})
.then(res => {
window.location.href = '/myOrders';
})
.catch(err => {
console.log(err);
})
})
.catch(err => {
console.log(err);
});
Here the axios.post works but the axios.delete does not. The page is getting redirected.
In the next code, again the axios.delete does not work.
axios.get('/api/getuser/')
.then(res => {
user_id = res.data.id;
console.log("Id Received");
})
.then(res => {
axios.delete("/api/cart/" + user_id + '/' + this.props.id)
.then(res => {
console.log("Product Deleted");
})
.then(res => {
window.location.href = '/cart';
})
.catch(err => {
console.log(err);
})
})
.catch(err => {
console.log(err);
});
Can someone please point out what the issue is or suggest a work-around?
It worked when I put the redirection statement in the first then function itself. It seems all the thens are triggered simultaneously. Because of this, the second then was triggered before the first.