Populate dropdown on React from JSON Data WebAPI - reactjs

I have a react form that has several dropdowns and it was working, however, the WebAPI changed and now the data is being returned slightly different and now none of the dropdowns are populated.
The old JSON format was like:
{
"data":
[{
"id" : 1,
"name" : "Michelle Smith",
},
{
"id" : 2,
"name" : "Jenn Arnold"
}
]
}
the drop down binding is:
const [ admins, setAdmin] = useState([]);
useEffect(() => {
getAdmins();
},[]);
//calls a JS file that connects to the API using axios
const getAdmins = () => {
adminGroups.GetAllAdmins()
.then((response) => {
setAdmins(response.data.data)
}
}
return (
<select>
<option>...</option>
{admins.map(data => {
<option
value={admin.id}
>
{admins.name}
<option>
</select>
)
The new JSON format is:
[{
"id" : 1,
"name" : "Michelle Smith",
},
{
"id" : 2,
"name" : "Jenn Arnold"
}]
There is no parent "data" tag in the new format, what would've caused the drop downs to stop binding with the new format? When the page loads, I can see the API being called (under the network tab) and if I go to the URL I can see data, just not in the React App. Is there another way I should be binding the dropdown?
[I'm fairly new to React and converting an Access app over to the web using React as the UI]

If all that's changed is that the API you're using no longer wraps the array in data then just don't go looking for it in your response.data.data use,
Instead just use response.data like so
const getAdmins = () => {
adminGroups.GetAllAdmins()
.then((response) => {
setAdmins(response.data)
}
}

I got this working, just by shutting down VS and opening it back up again. Not sure if VS had something cached or not, but the API was returning data, just not the UI until I restarted it. Thanks all

Related

Use data from graphql response in React

I guess this is a simple issue, but I am stuck here for a while, so any advice may be helpful!
I have a react app and I am calling a GraphQL api (with apollo). Inside an arrow function component I have:
const [executeQuery, { data }] = useLazyQuery(GET_ALL_TASKS);
const findId = (step) => {
executeQuery({
variables: {
"query": {
"state": "CREATED",
"taskDefinitionId": "something"
}
}
})
}
The query is successful and in the browser inspect panel I get this as the graphql response:
{
"data" : {
"tasks" : [ {
"id" : "2251",
"name" : "some_name",
"__typename" : "Task"
} ]
}
}
In my code I want to use the retrieved id. How can I isolate the id from the response? When I am trying to access the data I get an undefined error.
Thank you!
Not sure why you are wrapping your executeQuery in a function.
The data will be part of the response so you can get it like this:
const {data, loading} = executeQuery({
variables: {
"query": {
"state": "CREATED",
"taskDefinitionId": "something"
}
}
})
// may also need to check for the error state
if(loading){
console.log("Loading...")
}else{
/// the ids seem to be an array of objects
const ids = data.tasks.map((task)=> task.id)
console.log(ids)
}
For anyone who may have the same problem, I realized it is a caching error happening in apollo client. I couldn't figure out the solution. However, I temporarily solved it by downgrading the apollo client dependency to version 3.2.5

Updating state when database gets updated

I got a schema looking something like this:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
//Create Schema
const PhoneNumbersSchema = new Schema({
phone_numbers: {
phone_number: 072382838232
code: ""
used: false
},
});
module.exports = PhoneNumbers = mongoose.model(
"phonenumbers",
PhoneNumbersSchema
);
And then I got an end-point that gets called from a 3rd party application that looks like this:
let result = await PhoneNumbers.findOneAndUpdate(
{ country_name: phoneNumberCountry },
{ $set: {"phone_numbers.$[elem1].services.$[elem2].sms_code": 393} },
{ arrayFilters: [ { "elem1.phone_number": simNumberUsed }, { "elem2.service_name": "steam" } ] },
Basically the end-point updates the "code" from the phone numbers in the database.
In react this is how I retrieve my phone numbers from the state:
const phonenumbers_database = useSelector((state) => {
console.log(state);
return state.phonenumbers ? state.phonenumbers.phone_numbers_details : [];
});
Every time the code gets changed in my database from the API call I would like to update "phonenumbers_database" in my state automatically.
How would I be able to do that?
MongoDB can actually watch for changes to a collection or a DB by opening a Change Stream.
First, you would open up a WebSocket from your React app to the server using something like Socket.io, and then watch for changes on your model:
PhoneNumbers
.watch()
.on('change', data => socket.emit('phoneNumberUpdated', data));
Your third party app will make the changes to the database to your API, and then the changes will be automatically pushed back to the client.
You could do a polling and check the Database every N secs or by using change streams
After that, to notify your frontend app, you need to use WebSockets, check on Socket IO

How to use custom field in react admin, insted of { data: [...] }

I'm new in react-admin and I'm trying to create a new admin panel for my old API.
So when my data provider do API calls it causes me this error:
The response to 'getList' must be like { data : [...] }, but the received data is not an array. The dataProvider is probably wrong for 'getList'
The responses of my old API has various data fields like { 'posts': [] } or { 'users': [] }. How can I use these name of fields instead of { 'data': [] } ?
The 'data' in this case just refers to the type of information that should be retuned, not the name of the object.
Within your API, you can simply return a list in the following form:
const posts = [
{
"id":1,
"name":"post1"
},
{
"id":2,
"name":"post2"
},
];
return JSON.stringify(posts);
Then return that 'posts' object in your response and don't forget to set the expected ContentRange headers.
Not sure what language you are using, but the principle above should be easy enough to follow and apply in any language.

How to render Draft-js text in React from server

I using Draft-js to build my text-editor.
What I want to do is on clicking the submit button, the submitted text should appear on right side (as you can see, the blank side)
I'm calling a handleSubmit function to post the content to server:
handleSubmit = e => {
e.preventDefault();
const query = JSON.stringify(convertToRaw(this.state.editorState.getCurrentContent()));
const payload = {
query:query
}
axios({
url:'http://localhost:9000/queries',
method:'POST',
data: payload
})
}
and to retrieve the content :
getQueries(){
axios.get("http://localhost:9000/queries")
.then(response => {
const data = response.data;
this.setState({queries:data});
})
}
I'm bit confused, on how to use convertFromRaw to convert the content to the desired text.
Where should I call the method ?
Thanks in advance
You have to understand that DraftJS is a library that converts whatever you have inside the editor into it own format.
For Example, apple is converted to,
{
"blocks": [{
"key": "f6b3g",
"text": "apple",
"type": "unstyled",
"depth": 0,
"inlineStyleRanges": [{
"offset": 0,
"length": 5,
"style": "ITALIC"
}],
"entityRanges": [],
"data": {}
}],
"entityMap": {}
}
Yep, it's that big. So, in order to convert it back from this format to apple you need a component which knows how to interpret it. You cannot just use a div tag. In this case, it's the editor component itself!
So you can do the following to display the content in readonly mode.
<Editor readOnly={true}
editorState={EditorState.createWithContent(this.state.editorState.getCurrentContent())}/>
Now, say if you want to send the editor contents to an API so that you can save it in DB and then get the content from the API and display it.
Convert from Editor Format to JSON
const requestBody = JSON.stringify(convertToRaw(this.state.editorState.getCurrentContent()))
Post JSON to your API
fetch(url, {
method: 'POST',
body: requestBody
});
Get JSON from your API
const response = await fetch(url, {
method: 'GET'
});
Convert from JSON to Editor format and display using Editor (You can remove readonly if you want the user to edit the contents)
<Editor readOnly={true}
editorState={EditorState.createWithContent(convertFromRaw(JSON.parse(response))}/>

How to set up admin-on-rest with couchDB?

Edit to the makers of AoR : Your framework suffers from horrid documentation. You should really focus on that, people would really adopt it then.
I cant for the life of me decipher how admin-on-rest does the 'rest' part. If there is a better framework with better documentation, Im open to that.
Im very new to react, so thats probably part of it.
What I can discern is that
1) The [Admin] tag takes a prop 'restClient', and this is a function that sets your base path to your JSON source, then returns a function with a specific signature (takes 3 arguments, returns a promise).
2) Then a [Resource] tag adds to the path with name="posts" and makes a list, which (heres where it turns to magic) basically does a wget to your database then iterates over the results.
What I want to do : hook up couchDB to admin-on-rest. I already have a few test docs made on localhost. The couchDB url looks like :
http://127.0.0.1:5984/myproject/_design/getclients/_view/getclient/
and this works in postman, giving me a json object like this :
{
"total_rows": 4,
"offset": 0,
"rows": [
{
"id": "afc3bb9218d1a5c1e81ab3cc9f004467",
"key": {
"status": "active",
"rating": 9.1,
"bio": {
"fname": "Sam",
"mname": "TestMName",
"lname": "TestLName",
"address": "712347 B Street",
"state": "CA",
"city": "Los Santos",
"zip": "90211",
"phone": "123-456-7890",
"email": "sam#samsemail.com",
"username": "TestSam",
"password": "abc123"
}
},
"value": null
},
At this point Im so confused I dont know where to look.
Heres my code now :
//App.js
import React from 'react';
import { jsonServerRestClient, Admin, Resource } from 'admin-on-rest';
import { PostList } from './Posts.js';
const App = () => (
<Admin restClient={jsonServerRestClient('http://127.0.0.1:5984/myproject/')}>
<Resource name="_design/getclients/_view/getclient" list={PostList} />
</Admin>
);
export default App;
And
//Posts.js
export const PostList = (props) => (
<List {...props}>
<Datagrid>
<TextField source="status" />
<TextField source="rating" />
</Datagrid>
</List>
);
The page loads but a little pink box pops up at the bottom saying :
The X-Total-Count header is missing in the HTTP Response. The jsonServer REST client expects responses
The RestClient is a bit of a murky beast. Not perfectly documented for sure.
But it is in the end quite straightforward if you know how the whole thing works together.
1) Admin-On-Rest has defined some REST types (below). These are usually shot off by Redux actions (in their meta tag). The system scans for these rest types and if it sees them, then it calls the RestClient
GET_LIST
GET_ONE
CREATE
UPDATE
DELETE
GET_MANY
GET_MANY_REFERENCE
The REST client is called with these types and some other params. It is the job of the rest client to interpret the type and then use the params to make a request to your API. For this AOR uses the new Fetch API that is built into browsers.
You can access it by calling. You should also go into AOR source code and check out how it works.
import { fetchUtils } from 'admin-on-rest';
2) The X total count is a header field that AOR needs for all responses to the GET_LIST type.
You can set this quite simply in your API. I use loopback and I set the X-Total-Count manually in a remote hook (don't worry about it if you don't know it)
It seems your api is still using the JSON server. JSON server is a dummy API. So your app is not connected to your couchDB right now.
https://github.com/typicode/json-server
If you are not using an api server like express or loopback, then you can also configure your restClient do all request and response handling. You have to construct the URL. Read the below link so you can follow my example code further down.
https://marmelab.com/admin-on-rest/RestClients.html#decorating-your-rest-client-example-of-file-upload
so something like this.
if (type === 'GET_LIST' && resource === 'posts') {
const url = http://127.0.0.1:5984/myproject/_design/getclients/_view/getclient/
options.method = 'GET';
return fetchUtils.fetchJson(url, options)
.then((response) => {
const {headers, json} = response;
//admin on rest needs the {data} key
return {data: json,
total: parseInt(headers.get('x-total-count').split('/').pop(), 10)}
})
You can also write a function like this to handle the request and response.
function handleRequestAndResponse(url, options={}) {
return fetchUtils.fetchJson(url, options)
.then((response) => {
const {headers, json} = response;
//admin on rest needs the {data} key
const data = {data: json}
if (headers.get('x-total-count')) {
data.total = parseInt(headers.get('x-total-count').split('/').pop(), 10)
} else {
data.total = json.length // this is why the X-Total-Count is needed by Aor
}
}
}
// handle get_list responses
return {data: json,
total: } else {
return data
}
})
}
The above code has been formatted in the window and so might not work straight out of the box. But I hope you get the idea.

Resources