How to make api function dynamically in Reactjs - javascript

I am working with Reactjs/Nextjs and i am fetching data from "comments.js"
in this file right now data is statically displaying,Here is my current data
export const books = [
{
id: 1,
title: "Things fall apart",
},
{
id: 2,
title: "Fairy tails",
},
...
]
I want to know that how can i convert this "static" data to "dynamic"(from server or database/mysql) ?

Related

How can I modify and extend properties of an object located in useState Array?

I'm a react.js beginner, searching for methods to alter my data structure. For example, I want to push new objects into the children-array or remove them by key.
What is the appropriate way to do that?
const [treeData, setTreeData] = useState([
{
title: "parent 1",
key: "0-0",
icon: <UserAddOutlined />,
children: [
{
title: "parent 1-0",
key: "0-0-0",
icon: <UserAddOutlined />,
children: [
{
title: "leaf",
key: "0-0-0-0",
icon: <UserAddOutlined />,
},
{
title: "leaf",
key: "0-0-0-1",
icon: <UserAddOutlined />,
},
],
},
{
title: "parent 1-1",
key: "0-0-1",
icon: <UserAddOutlined />,
children: [
{
title: "sss",
key: "0-0-1-0",
icon: <UserAddOutlined />,
},
],
},
],
},
]);
So you should not update the state directly. It is not allowed.
Maybe where you are receiving data from, suppose via api and the data is response.payload.data etc.
So in your case use the setTreeData(response.payload.data) method to add stuff in it.
Now if you want to update certain value (remove or update using index etc). Obviously you will have to have index somehow.
So for deleting say you will have some click and against that a handler for it
removeItem(e) {
item_to_remove = e.target..... etc // to get the item's reference for matching
setTreeData(treeData.filter(items => item.<someproperty> != item_to_remove))
// In your case could also be targetting children maybe
// setTreeData(treeData.Children.filter(items => item.<someproperty> != item_to_remove))
}
I would say maybe handle childrens' array inside another useState variable (childrenTreeData maybe). But you will have to look it's feasibility too. Just an idea after seeing your data
JUST for INFO
This is something similar I did for updating prices inside each cards in my project
const getCurrentPrice = useCallback(() => { // <======= maybe you do not need this
const updatedTilesData = tilesData.map((tile: any) => {
return {
...tile, // <======= get everything here and then update the price below for item
currentPrice: calculateDNCurrentPrice(
tile.startingPrice,
tile.dnTimestamp
),
};
});
setTilesData(updatedTilesData);
}, [tilesData]);

Unable to output useState to imported chart

I have a simple form where i will add a task and add the amount of minutes that task has taken, i am having trouble trying to get the chart which i have imported from 'Recharts' to see the state, it looks like the state is returning an empty array and my chart is not seeing the data.
The Recharts chart takes an array with an object inside with two values, example shown below
const data = [
{ name: "Group A", data: 400 },
{ name: "Group B", data: 300 },
{ name: "Group C", data: 300 },
{ name: "Group D", data: 200 },
{ name: "Group E", data: 278 },
{ name: "Test Data", data: 189 }
];
However after i have moved my state as props to the component and mapped the result to take the same names as input the charts is not displaying anything
(my mapped props)
const activityData = [
...props.pieData.map(el => ({
name: el.title,
data: el.amount
}))
];
I have put a simplified version on codesandbox to make it a little bit easier if anyone wants to see the output i'm getting
https://codesandbox.io/s/hidden-dew-676xc
Found the issue as soon as i posted this, the 'data' value which i had mapped in my props was getting outputted as a string, when the object was expecting a number

How to assign a JSON string to a google pie chart data var

The problem I am facing is that in my web server I am sending a JSON as argument via render_template to my website where I want to use that JSON to show a google pie chart.
The problem is that if I assign the google pie chart data statically like this:
var data = new google.visualization.DataTable({
cols: [
{ id: "", label: "objeto", type: "string" },
{ id: "", label: "quantidade", type: "number" }
],
rows: [
{ c: [{ v: "Caixa 2" }, { v: 3 }] },
{ c: [{ v: "Caixa 3" }, { v: 3 }] },
{ c: [{ v: "Caixa 4" }, { v: 3 }] }
]
});
It works perfectly. On the other hand if I assign it dynamically with the JSON that I am receiving from my server like this:
var data = new google.visualization.DataTable({{json}});
It stops showing the google pie chart in my website.
The things I tried until now was litteraly adapting the JSON to the desired format by google charts because I thought that was the only problem, but now that it is in the required format and it works statically I do not know any way of assigning my received JSON to the data var.
This is my ideal function that I would like to work.
function drawChart() {
var data = new google.visualization.DataTable({{json}});
var options = {
title: 'gráfico Objeto/Quantidade',
is3D: true
};
var chart = new google.visualization.PieChart(
document.getElementById('piechart')
);
chart.draw(data, options);
}
Desired result:
http://prntscr.com/oejojv
Actual result:
http://prntscr.com/oejooe
The JSON string is being HTML-escaped. Assuming that you're using Flask (guessing based on your mention of render_template), you need to do something like {{json | safe}}.
Also, this assumes that you have total control over the content of this JSON, because you are otherwise susceptible to cross-site scripting attacks.

Two Way Link Using Normalizr

I have a list of regions, which I get from an API. In this list, there are multiple buildings. This will look like this in JS:
const regions = [
{
guid: 'REGION1-GUID',
name: 'Region 1',
buildings: [
{
guid: 'REGION1-BUILDING1-GUID',
name: 'Region 1 Building 1'
},
{
guid: 'REGION1-BUILDING2-GUID',
name: 'Region 1 Building 2'
}
]
},
{
guid: 'REGION2-GUID',
name: 'Region 2',
buildings: [
{
guid: 'REGION2-BUILDING1-GUID',
name: 'Region 2 Building 1'
},
{
guid: 'REGION2-BUIDLING2-GUID',
name: 'Region 2 Building 2'
}
]
}
];
Now I want to normalize this JS Object using normalizr. What I want to do later is to get the region from a building.
So I tried to do the following:
// Define the buildings schema
const building = new schema.Entity('building', {}, { idAttribute: 'guid' });
// Define the regions schema
const region = new schema.Entity(
'regions',
{
buildings: [building]
},
{ idAttribute: 'guid' }
);
const regionList = [region];
const normalizeData = () => {
const normalizedData = normalize(data, regionList);
This does normalize my object, the normalizedData is like this:
{
"entities":{
"building":{
"REGION1-BUILDING1-GUID":{
"guid":"REGION1-BUILDING1-GUID",
"name":"Region 1 Building 1"
},
"REGION1-BUILDING2-GUID":{
"guid":"REGION1-BUILDING2-GUID",
"name":"Region 1 Building 2"
},
"REGION2-BUILDING1-GUID":{
"guid":"REGION2-BUILDING1-GUID",
"name":"Region 2 Building 1"
},
"REGION2-BUIDLING2-GUID":{
"guid":"REGION2-BUIDLING2-GUID",
"name":"Region 2 Building 2"
}
},
"regions":{
"REGION1-GUID":{
"guid":"REGION1-GUID",
"name":"Region 1",
"buildings":[
"REGION1-BUILDING1-GUID",
"REGION1-BUILDING2-GUID"
]
},
"REGION2-GUID":{
"guid":"REGION2-GUID",
"name":"Region 2",
"buildings":[
"REGION2-BUILDING1-GUID",
"REGION2-BUIDLING2-GUID"
]
}
}
},
"result":[
"REGION1-GUID",
"REGION2-GUID"
]
}
But to get the Region of a building i need to iterate over every region and check if the building is contained in the list. I will not get any added value trough the normalization.
It would be perfect if I am able to link in both direction. Every region entitiy has a list of building guids and every building has one region guid.
Is there any way to archieve this in normalizr? What would be the best approach?
Thank you for your help.
I tried some things and found a working solution. I don't know if there is any better approach, but it's very clean code and it's working.
I just had to change the definition of the building entity to:
// Define buildings schema
const building = new schema.Entity(
'building',
{},
{
idAttribute: 'guid',
processStrategy: (entity, parent) => ({ ...entity, regionGuid: parent.guid })
}
);
This will add the property "regionGuid" to the building which holds the guid from the region.

Custom paging with array of JavaScript objects

I am working on a application which is nicely modularized using requirejs. One of the modules called data service is in charge of providing other modules with data. Pretty much all get* methods of this module return javascript script objects in the the following format:
res = {
totalRows: 537,
pageSize: 10,
page: 15,
rows: [
{
id: 1,
name: 'Angelina'
...
},
{
id: 2,
name: 'Halle'
...
},
{
id: 3,
name: 'Scarlet'
...
},
{
id: 4,
name: 'Rihanna'
...
},
{
id: 5,
name: 'Shakira'
...
},
....
//10 rows
{
id: 10,
name: 'Kate'
...
}
]
}
Is it possible to initialize the data table by providing it with rows for the current page, current page number, page size and the total number of records or pages so that it "knows" which page is currently being displayed as well as the number of available pages. Which in turn would allow the DT to build the pager correctly allowing the user to navigate to other pages in which case we would make another call to data service module to retrieve data from the database for the selected page.

Categories