How to fetch the response of JSON array in react native? - json

rq.js
}).then((responseData) =>{
this.setState({
user:responseData.name,
user1:responseData.blood,
user2:responseData.location,
loaded: true,
})
This is my code in react native.It works perfect if my JSON response is not an array.What change do i need to make in this code to work perfectly if json is an array?Showing this error Unexpected token < in JSON at position 1
data.json
[{"name":"hema","bld":"O -ve","lc":"london"}]
this is my json array input.Anybody please help..

try sending the data as a object not as array
{"name":"hema","bld":"O -ve","lc":"london"}
and actually you are calling props blood and location, but your JSON content bld and lc for that props

If You want it work with an array just do
}).then((responseData) =>{
this.setState({
user:responseData[0].name,
user1:responseData[0].blood,
user2:responseData[0].location,
loaded: true,
})
in this way you are calling the first object of the array's index and then the prop of this first object in the array

I know it's too late, but I hope it's helpful for others. How to fetch the response of JSON array in react native?
export default class ExpenseNew extends Component {
constructor(){
super();
this.state={
accountnameMain:[],
}
}
componentDidMount(){
var account_nam=[]
fetch('your Url', {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + your token }
})
.then((response) => response.json())
.then((customerselect) => {
// alert(JSON.stringify(customerselect))
global.customerdata = JSON.stringify(customerselect)
var customername = JSON.parse(customerdata);
//alert(JSON.stringify(customername));
for (i = 0; i < customername.cus_data.length; i++) {
var dataa = customername.cus_data[i]["account_name"];
account_nam.push(dataa)
}
this.setState({accountnameMain:account_nam});
})
.done();
}
account_name is my field/column name, in your case, your column name is bld so you can fetch all data and push in var type of array, then set data in state type of array, and map anywhere you want.

Related

Next JS Error serializing `.dehydratedState.queries[0].state.data.config.adapter` returned from `getServerSideProps

I am trying to use react-query to fetch data in getServerSideProps in Next JS but I keep getting this weird error:
Error: Error serializing `.dehydratedState.queries[0].state.data.config.adapter` returned from `getServerSideProps` in "/auth/google/callback".
Reason: `function` cannot be serialized as JSON. Please only return JSON serializable data types.
Here is my code:
// Packages
import { useRouter } from 'next/router'
import { dehydrate, QueryClient, useQuery } from 'react-query';
// APIs
import { completeGoogleAuth } from '../../../hooks/auth';
export async function getServerSideProps(context) {
const queryClient = new QueryClient()
await queryClient.prefetchQuery('completeGoogleAuth', () => completeGoogleAuth(context.query.code));
return {
props: {
dehydratedState: dehydrate(queryClient),
},
}
}
export default function Callback() {
const router = useRouter();
const { data } = useQuery('completeGoogleAuth', () => completeGoogleAuth(router.query.code))
return (
<>
Loading
</>
)
}
I have tried to use JSON.stringify(dehydrate(queryClient)) and also used JSON.parse(JSON.stringify(dehydrate(queryClient))) but none of them worked.
What can I do?
I stumbled across the same error just today, JSON.stringify(dehydrate(queryClient)) or serializing dehydrate(queryClient) by any means won't really work as the object your completeGoogleAuth function is returning has function values in the key-value pairs, here's a picture of the config object.
And as you know, functions can't be JSON serialized as straightforwardly. Now, what I assume you used(or what I did too) for the completeGoogleAuth fetcher function is use Axios as your API client library. I have found that Axios returns objects that can't be JSON serialized. As a solution, I have just used the native JavaScript fetch() API to get API data and the haven't faced any issues since then.
Here's my fetcher function:
export const getScholarshipInfoSSR = async (token) => {
const response = await fetch(
process.env.NEXT_PUBLIC_API_BASE_URL + portalRoutes.getScholarshipInfo,
{
headers: { Authorization: `JWT ${token}` },
}
);
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json().then((data) => ({ data }));
};
Here's the prefetched useQuery invocation:
await queryClient.prefetchQuery("portal", () =>
getScholarshipInfoSSR(token)
);

Trying to dispatch an axios action with a string array as the payload, but keep getting 'undefined' at the reducer?

I'm new to web development and as part of a project have made a Django React Redux app. The frontentd has a component with form entry - when a form is submitted, the component calls an action that sends an axios request to a python twitter crawler script in the backend. The script returns a response containing a string array (the tweets are inside the array). I then try to dispatch the array contained in the response.data, as a payload to a reducer. However I keep getting an error saying that the payload of what I have dispatched is undefined.
This is the return statement of the python method that is called - corpus is a string array.
return JsonResponse({"results:": corpus})
This is the code for the action that sends a GET request to the python method. It's then returned the string array inside a json object.
// GET_TWEETS - get list of tweets from hashtag search
export const getTweets = (hashtag) => dispatch => {
axios
.get('http://localhost:8000/twitter_search', {
params: {text: hashtag}
})
.then(res => {
console.log(res.data); //check if python method returns corpus of tweets
//const results = Array.from(res.data.results);
dispatch({
type: GET_TWEET,
payload: res.data.results
});
})
.catch(err => console.log(err));
}
The console log shows that the object is returned successfully from the python script.
console log
This is the code for my reducer. I want my action to contain the string array and then assign that string array to 'tweets' in the state, so that I can return this to a component and then access the array from the component and then display contents of thisx array of tweets on the frontend
import { GET_TWEET } from '../actions/types';
const initialState = {
tweets: []
}
export default function(state = initialState, action) {
console.log(action.payload)
switch(action.type) {
case GET_TWEET:
return {
...state,
tweets: [...action.payload]
}
default:
return state;
}
}
Also, this is some of the code for the component that I want to receive the string array, I hope I have set this part up properly:
export class Tweets extends Component {
static propTypes = {
tweets: PropTypes.array.isRequired,
getTweets: PropTypes.func.isRequired
}
...
const mapStateToProps = state => ({
tweets: state.TweetsReducer.tweets
});
export default connect(mapStateToProps, { getTweets })(Tweets);
Here is the error I get from the console. Console logging the payload of the action also shows that its value is undefined: undefined error
I've been trying to solve this for several days now, but am completely lost and I have a hunch the solution to this is pretty simple...

Angular Http JSON response Mapping

I am trying to map a Http JSON Response to a Custom Interface in Angular / typescript. I have tried it in several ways but have not made it yet. The JSON object is not correctly mapped to the interface. The map attribute stays "undefined". If I print the data directly, the JSON data is output correctly - the problem is that I don't know how to access it. Here is my code:
export interface IMap<T> {
map: Map<string, Array<T>>;
}
The JSON answer looks like this. It is Map< String,List< ? >> in Java.
{
"somenumbers": [
20,
40
],
"somemorenumbers": [
71,
111
]
}
Now I tried to map it the following way:
public getValues(
paramList: Array<string>
): Observable<IMap<any>> {
const url = `url`;
let params = new HttpParams();
for (let s of paramList) {
params = params.append("params", s);
}
return this.http.get<IMap<any>>(url, { params });
}
In the configservice I subscribe to the Method. How do I map the Response correctly so that the attribute map in data isn't undefined and can be accessed correctly?
this.configService
.getValues(["somenumbers", "somemorenumbers"])
.subscribe((data: IMap<any>) => {
//outputs the JSON Data as Object{somenumbers: Array(2), somemorenumbers: Array(2), map: Map(0)}
console.error(data);
console.error(data.map);//map is undefined => ERROR
});
As you can see the map attribute is undefined. It is just a "map: Map(0)". Now... - How do I get the JSON stuff into the export interface? The map attribute should be filled with the associated values.
I appreciate any help! :)
If I understood correctly you're expecting that by adding <IMap<any>> to the get call it will then return you the response mapped to IMap. It doesn't, check this issue.
What you can do instead is use rxjs map to map the response yourself like so:
return this.http.get<IMap<any>>(url, { params }).pipe(
map((response) => {
// map the response here
})
);
I realized that I actually don't need the export interface and changed the code to the following. It took a while for me to get that x.y is in ts the same as x["y"]. Via response[parameter] I can access the attributes of the response Object dynamically - exactly what I needed.
public getValues(
paramList: Array<string>
): Observable<Map<string, Array<any>>> {
const url = `url`;
let params = new HttpParams();
for (let s of paramList) {
params = params.append("params", s);
}
return this.http
.get<any>(url, {
params
})
.pipe(
map(response => {
let toReturn = new Map<string, any[]>();
for (let parameter of paramList) {
toReturn.set(parameter, response[parameter]);
}
return toReturn;
})
);
}
The mapping works now! The JSON answer is still the same as in the question above.
this.configService
.getValues(["somenumbers", "somemorenumbers"])
.subscribe((data: Map<string, any[]>) => {
console.error(data);
});
Thanks for the help and links #M Mansour !

Getting undefined when json fetch in react native

In my simplified code below I am able to pull data in JSON format but if I try to console log a specific key of the object, I get undefined.
I had thought I could use this.state.profile.name to display "Steven".
Why is this coming up as undefined when I'm able to see the entire response? Thanks!
state = {
responseJSON: null,
};
callGraph = async token => {
const response = await fetch(
`https://graph.facebook.com/me?access_token=${token}&fields=id,name,email,about,picture`
);
const responseJSON = JSON.stringify(await response.json());
this.setState({
profile: responseJSON
});
console.log("profile = " + this.state.profile);
};
this console.log output the following:
profile = {"id":"*******","name":"Steven *******","email":"steve#*******.com","picture":{"data":{"height":50,"is_silhouette":false,"url":"https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=*******&height=50&width=50&ext=1539943832&hash=AeQM2VfUBmdfOVJZ","width":50}}}
setState is asynchronous.
In your code, you are trying to console.log before the state is updated.
You need to use the callback as the second argument of the setState function:
this.setState({
profile: responseJSON
}, () => {
console.log("profile = " + this.state.profile);
});
Check this post for more information or also this other question
setState is asynchronous. The answer of Kevin is completely right. However, you can also use this method to see the result immediately:
this.profile= responseJSON;
console.log("profile = " + this.profile);
You should also define it in the constructor like this:
constructor(props) {
super(props);
this.profile='';
}
Also, in order to access the parameter of profile in your screen you need to use this.profile.

How to get data from parsedJSON reactJS

I'm setting up a basic WebApp here using ReactJS. Right now I can add data to my database using POST request no problem, the thing, my backend response sends me a JSON with all the data that I passed and the _id in the database. I need to get this _id and save it in my state so I can pass it along to the next URL in my WebApp. That's the code for my POST request :
SubmitClick(){
if (this.state.password !== this.state.reTypepassword){
alert('Passwords do not match. Please check your data !');
} else {
//console.log(this.state); //debug only
fetch('http://localhost:4000/users/', {
method: 'POST',
headers: {
'Accept': 'application/json',
//'Authorization': 'Basic YWRtaW46c3VwZXJzZWNyZXQ=',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: this.state.email,
first_name: this.state.first_name,
last_name: this.state.last_name,
personal_phone: this.state.personal_phone,
password: this.state.password
})
})
.then(response => response.json())
.then(parsedJSON => console.log(parsedJSON._id))
.catch(error => alert('Check your data', error))
.then(this.props.history.push('/get')) // change page layout and URL
}
console.log(this.state.id); //debug to see if the _id is saved in my state
}
Here is my constructor:
constructor(props){
super(props);
this.state={
email:'',
first_name:'',
last_name:'',
personal_phone:'',
password:'',
reTypepassword:'',
id:''
}
}
I tried calling a function after parsedJSON that used this.setState(), using function(parsedJSON){this.state.id : parsedJSON._id}. I tried with a new function like this:
changeID(parsedJSON){
this.setState({id : parsedJSON._id})
}
and changing the .then(parsedJSON => console.log(parsedJSON._id)) to .then(parsedJSON => this.cahngeID(parsedJSON)). But none of then worked...
I left the code with .then(parsedJSON => console.log(parsedJSON._id)) so can make sure that I can see this value, and in my console it`s printed perfectly.
Here is a example of the response send by my backend: {"email":"testing#gmail.com","first_name":"TESTER","last_name":"Testing","personal_phone":"(55) 2020-5252","password":"12345","_id":"5a27f511cd7d7a0db8ab65b9"}
How can I get the "_id" from my response?
You should not touch the this.state property directly. React will throw an error if you do this because React needs to know when this.state has been updated so that it can keep track of the changes. It cannot do this if you manipulate the property directly. That's why we have React.Component#setState. The "shallow" version is the most commonly used, where you pass an object that will be merged into your state. For example, the following:
.then(parsedJSON => this.setState({ id: parsedJSON._id }))
is equivalent to:
Object.assign(this.state, { id: parsedJSON._id });
except that React gets to keep track of when the state is updated.
Note that setState is also asynchronous and takes a callback as the second parameter. You can read more about that here.
As per the comment below, this other Stack Overflow question was helpful to the OP (Why calling react setState method doesn't mutate the state immediately?)
At the end of your constructor add this line of code:
this.SubmitClick = this.SubmitClick.bind(this);
because JavaScript does not bind the instance value of 'this' to our methods.