React JS get data from database using axios.get(url) with param - reactjs

I'm trying to get data from a database using axios in React. Unfortunately for some reason the url I use doesn't return data although in the browser it does. The url contains a parameter, which is most likely a problem because when I use an url without a parameter, the data is returned.
constructor(props) {
super(props);
this.state = {
userId : this.props.match.params.userId,
users:[]
}
}
componentDidMount() {
const url = "http://localhost:8080/getUser?userId=1";
axios.get("http://localhost:8080/getUser", {params: {
userId: this.state.userId
}})
.then(response => response.data)
.then((data) => {
this.setState({users: data})
});
console.log(this.state.users);
}
Does anyone know how to get database data correctly using REST API and axios?

axios.get("http://localhost:8080/getUser", {
params: {
userId: this.state.userId
}
})
.then(response => response.json()) // You need to parse JSON
.then((data) => {
this.setState({users: data})
});
Only difference is in first .then, you need to parse data to JSON.

Related

Export variable from one file to another in react

I am currently working on a react-native based website and I am struggling to pass values from one file to another.
The value I am trying to import is 'Key':
class Encrypt extends Component {
encryptData = async() => {
fetch('http://localhost:7000/Data')
.then(res => res.json())
.then((data) => {
var pub1Key = data ;
var Key=pub1Key["encryptedData"];
}
And use it like this
class Decrypt extends Component {
deData(){
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({data: Key })
};
I tried to use export option but it didn't work.
These are two separate files. Encrypt.js and Decrypt.js.
You can manage this via any state manager. You can use Redux or Mobx or ReactContext for that.
However, if this is the token that is required for authentification or data that you want to access even after the page will be reloaded, you can simply store it in AsyncStorage.
So your code would look something like that.
import {AsyncStorage} from 'react-native';
class Encrypt extends Component {
encryptData = async() => {
fetch('http://localhost:7000/Data')
.then(res => res.json())
.then((data) => {
//you can decrypt 'data' here
return AsyncStorage.setItem('pub1Key', data);
})
.catch((err)=>{
//handle any errors here
})
}
class Decrypt extends Component {
async getData(){
return new Promise((resolve, reject)=> {
try{
const data = await AsyncStorage.setItem('pub1Key', data);
//you can encrypt data here
resolve(data);
} catch(e){
reject(e);
}
})
};
The docs for that.
https://reactnative.dev/docs/asyncstorage.html

How to save single object into state, from json end point axios

UPDATE:
axios
.get("https://cors-anywhere.herokuapp.com/" + "https://api.linkedin.com/v2/me", config)
.then(response => {
this.setState({profile: response.data})
})
^ saved the object in state for me :) Thanks everyone!!
I am a newbie to react. I am trying to save a single object from a JSON end point into the state of my react component. I am definitely returning the JSON data in the response. However it is not being saved into the state, can you see where I am going wrong?
// State needed for the component
constructor(props) {
super(props);
this.state = {
profile: {},
};
}
// Grabs profile data from the json url
private getProfile() {
let config = {
headers: {'Authorization':'Bearer AQVVEqNXTWV....'}
}
axios
.get("https://cors-anywhere.herokuapp.com/" + "https://api.linkedin.com/v2/me", config)
.then(response =>
response.data(profile => ({
id: `${ profile.id }`
}))
)
.then(profile => {
this.setState({
profile
});
})
// We can still use the `.catch()` method since axios is promise-based
.catch(error => this.setState({ error, isLoading: false }));
}
JOSN data returned:
{
"localizedLastName": "King",
"id": "fm0B3D6y3I",
"localizedFirstName": "Benn"
}
Your first then block looks wrong.
Try to do console.log there like this:
.then(response => {
console.log(response); // I am sure that you will get profile inside response.data or something similar
return response.data(profile => ({
id: `${ profile.id }`
}));
})
If you want to keep your first then that "prepares the data", then you should return a promise instead of data, like:
let config = {
headers: {'Authorization':'Bearer AQVVEqNXTWV....'}
}
axios
.get("https://cors-anywhere.herokuapp.com/" + "https://api.linkedin.com/v2/me", config)
.then(response => {
return new Promise((resolve, reject) => {
resolve( {
id: `${ response.data.id }`
});
});
}
)
.then(profile => {
this.setState({
profile
});
})
// We can still use the `.catch()` method since axios is promise-based
.catch(error => this.setState({ error, isLoading: false }));
Here's an example of how that would work:
I do believe that's a bit of an overkill though and you should be able to just set your state in the first then such as:
this.setState({profile: {id : response.data.id}});
Try to remove the second then, like this:
axios
.get("https://cors-anywhere.herokuapp.com/" + "https://api.linkedin.com/v2/me", config)
.then(response => {this.setState({ profile: response.data })};
})
}))

How to Display quoteText from the response of this API Object

Random Quote
How to display the quoteText and quoteAuthor separately from this object for my random quote machine app.I have tried the standard way by writing {this.state.quote.quoteText}.
Here is the response object that I have got from my API.
1:[response object of API]
+Code Snippets
2:[code snippet-1]
3:[code snippet-2]
May be when the component is mounted your data is not yet fetched so here is one possible solution. On line number 37 where you have done this
{this.state.quote !== null && <p>{this.state.quote}</p>}
Instead Try this
this.state.quote.quoteText ? this.state.quote.quoteText : "";
Also on line number 23 where you have done this
axions.get("the url")
.then((res) => { this.setState({
quote: res.data
})
})
Add this line of code
.then((response) => response.json())
so your code will look like this
axions.get("the url")
.then((response) => response.json())
.then((res) => {
this.setState({
quote: res.data
})
})
**Even if that fails try this code that uses fetch **
fetch("the url goes here", {
method: 'GET'
})
.then((response) => response.json())
.then((data) => {
this.setState({
quote: data.response
})
you can call this fetch API directly in componentDidMount() lifecycle .

How to retrieve data from promise object in React JS

I am trying to get data from an API. But the fetch result is returned as promise object. I want to return the contents from this promise to invoke react action.
let loginData = fetch(loginURL, { method : 'POST', headers : headerParams,
body: bodyParams })
.then((response) => response.json())
.then(data => {
return data['retrieve-agent'];
});
console.log('loginData ===>', loginData.agent);
return {
type: 'GET_AGENT_DETAILS',
payload: loginData
}
Make use of async-await to get the result without using a promise or else you would need to resolve the promise from the function
async fetchFunction() {
let loginData = await fetch(loginURL, { method : 'POST', headers : headerParams,
body: bodyParams })
.then((response) => response.json())
.then(data => {
return data['retrieve-agent'];
});
console.log('loginData ===>', loginData.agent);
return {
type: 'GET_AGENT_DETAILS',
payload: loginData
}
}

React fetch method is returning json as object rather than array

In my main component, I am fetching the api data and setting it to a state. Rather than an object, I'd prefer it to be in an array. Is there any way I can do this during the fetch and just make the object the first index(and only) index in an array?
fetch('https://api.aes/latest')
.then(response => {
return response.json();
})
.then(json => {
this.setState({
launchData: json,
});
You can use React#spread operator on object.
.then(json => {
this.setState({
launchData: [...json],
});
You might try
fetch('https://api.aes/latest')
.then(response => {
return response.json();
})
.then(json => {
this.setState({
launchData: [json],
});

Resources