Axios Async Multiple Request Vue.js Rendering Problem - javascript

I am trying to fetch data from different 2 json.
json for data1: [{ id: 1, name: 'abc'},{id:2, name: 'def'}] json for
data2: [{ product_id: 0001, },{product_id:0002}]
By using these I would like to create this kind of structure.
myStore = [ { id: 1, name: 'abc', products: [{ product_id: 0001,
},{product_id:0002}]}, { id: 2, name: 'def', products: [{ product_id:
0003, },{product_id:0004}]}
<script>
export default {
data: () => ({
myStore: [],
isLoaded: false,
}),
created(){
this.fetchData()
},
watch: {
'$route': 'fetchData'
},
methods: {
fetchData() {
axios.get('api/data1')
.then(response => {
this.myStore = response.data
})
.catch(error => {
console.log(error);
})
.then(() => {
this.myStore.forEach(subStore => {
axios.get('api/data2?substore_id=' + subStore.id)
.then(response => {
this.myStore.products = response.data
})
.catch(error => {
console.log(error);
})
});
})
this.isLoaded = true;
},
},
}
I checked console.log, the structure that I want to have is created correctly however the problem is about rendering.
I tried to render {{myStore}}, I can only see the first data (data1) results [{ id: 1, name: 'abc'},{id:2, name: 'def'}]
When I update any code without reload page (via F5), vue updates this change. This time I can see the structure correctly that I wanna have. But when I reload page all is gone.

Related

row data from axios in material-table only render after refreshing the page

Currently I am facing a problem that the data from axios POST request to material-table will not render immdiately. I need to refresh it in order to show it. I have a axios request structure like this:
export default function DataWorker() {
const [entries, setEntries] = useState({
data: [
{
id: "",
position: "",
defect: "",
tool: ""
}
]
});
const [state] = React.useState({
columns: [
{ title: "Position", field: "position" },
{ title: "Defect Type", field: "defect" },
{ title: "Tool Decision", field: "tool" }
]
});
const url = "http://127.0.0.1:8000/api/manual_ver_data/"
useEffect(() => {
axios.get(url)
.then(response => {
let data = [];
response.data.forEach(el => {
data.push({
id: el.id,
position: el.position,
defect: el.defect,
tool: el.tool
});
});
setEntries({ data: data });
})
}, []);
return (
<MaterialTable
columns={state.columns}
data={entries.data}
editable={{
onRowAdd: (newData) =>
new Promise(resolve => {
setTimeout(() => {
resolve();
const data = [...entries.data];
const populateData = (axiosResponse) => {data.push(axiosResponse)}
axiosCallBack(populateData)
console.log(data)
function axiosCallBack (populateData) {
axios.post(url, newData)
.then(function(res){
populateData(res.data)
})
};
setEntries({ ...entries, data });
}, 600)
})
}}
/>
)
};
This is my view.py:
#api_view(['GET', 'POST'])
def TableViewList(request):
if request.method == 'POST':
serializer = TabelSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
After checking the console.log(data), the data looks like this:
[]
0: {id: 197, position: 'Position 1', defect: 'Defect 1', tool: 'Tool 1'}
length: 1
[[Prototype]]: Array(0)
I found out that after refreshing the page, there is an additional dictionary key tableData.
[]0
0: {id: 197, position: 'Position 1', defect: 'Defect 1', tool: 'Tool 1', tableData: {…}}
length: 1
[[Prototype]]: Array(0)
tableData: {id: 0}
Seems like the material-table require tableData as a key to arrange the row data. But I really want to render the row data without refreshing, is it possible to include the tableData manually? and how to do that?

Building a gateway with nodeJs

I have to build a layer for an API using nodeJs and create some endpoints for the frontend.
I'm new to nodeJS and I've builded some small servers creating models and making some CRUD with Mongo.
This is the first time I have to make an intermediate layer to an existing API to filter the results.
I did it, and in the expected format, but I'm getting an error from node and I can't figure out how to resolve it.
The original API is kind like this:
{
id:'some id',
pagination: {...},
results: [...],
other_results: [...],
additional_info: [
{
id:'someid',
info:'someinfo',
values:[
{
id: 'someid',
name: 'some category name',
count: 999
},
{...},
{...}
],
},
{...},
{...}
]
}
and I have to "extract" the data from "results" and the first array of "additional_info".
My endpoint has to return data in this format:
{
brand: {name: "Any brand", country: "Germany"},
categories: ["category one", "category two", "category three"],
items: [
0: {id: "olmk23238777", name: "item one", imgUrl: 'img/34341.jpg', price: {total:424, currency: "USD"}, shipping: 'fast'},
1: {id: "olmk23239348", name: "item two", imgUrl: 'img/34764.jpg', price: {total:47, currency: "USD"}, shipping: 'slow'},
…]
}
I could achieved with this:
const axios = require('axios');
exports.products = async query => {
const url = `${process.env.BASE_URL}${query}`;
let productsData = {
brand: {
name: 'Any Brand',
country: 'Germany',
},
};
try {
const result = await axios({
method: 'GET',
url,
});
const data = result.data;
productsData.categories = data.additional_info[0].values.map(
({ categoryName }) => categoryName
);
productsData.items = data.results.map(item => ({
id: item.id,
name: item.name,
imgUrl: item.imgSrc,
price: {
total: parseInt(item.price),
currency: item.currency,
},
shipping: item.shipping_method,
}));
return productsData;
} catch (error) {
console.log(error);
}
};
This is the controller:
const { products } = require('../utils/products');
exports.searchItem = async (req, res) => {
const { search } = req.query;
try {
const response = await products(search);
res.send(response).json();
} catch (error) {
console.log(error);
}
};
and the endpoint look like this:
http://localhost:4000/api/products?search=shirt
This is the error
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
I tried different things but I can't fixe it
First of all, your error has an explanation here:
Error: Can't set headers after they are sent to the client
And for your code:
look this:
res.send(response).json();
it should be one of these:
res.send(response);
// or
res.json(response);
For the parameter type/structure, please refer to documentation of your selected library.

Next.js: getStaticPaths for nested dynamic routes

Imagine you have this data structure:
const data = {
posts: [{
id: 1,
title: "Post 1"
slug: "post-1"
}, {
id: 2,
title: "Post 2"
slug: "post-2"
}],
comments: [{
id: 1,
postId: "post-1",
text: "Comment 1 for Post 1"
}, {
id: 2,
postId: "post-1",
text: "Comment 2 for Post 1"
}, {
id: 3,
postId: "post-2",
text: "Comment 1 for Post 2"
}]
}
An you have the following route /posts/[postId[/[commentId]
so the Next.js structure folder is: posts/[postId]/[commented].js
Then you need to generate the static paths for this routes.
I'm coded the following:
export async function getStaticPaths() {
const { posts, comments } = data
const paths = posts.map((post) => {
return comments
.filter((comment) => comment.postId === post.slug)
.map((comment) => {
return {
params: {
postId: post.slug,
commentId: comment.id
}
}
})
})
}
But it's not working. The throwed error was:
Error: Additional keys were returned from `getStaticPaths` in page "/clases/[courseId]/[lessonId]". URL Parameters intended for this dynamic route must be nested under the `params` key, i.e.:
return { params: { postId: ..., commentId: ... } }
Keys that need to be moved: 0, 1.
How I can "map" or "loop" the data to a proper returned format?
Thanks in advance!
The problem seems to be that your returning this from getStaticPaths data with a wrong shape:
[
[ { params: {} }, { params: {} } ],
[ { params: {} } ]
]
The correct shape is:
[
{ params: {} },
{ params: {} },
{ params: {} }
]
Just tried this and it works.
export async function getStaticPaths() {
const paths = data.comments.map((comment) => {
return {
params: {
postId: comment.postId,
commentId: comment.id
}
}
});
console.log(paths);
return {
paths,
fallback: false
}
};
It generates 3 urls:
/posts/post-1/1
/posts/post-1/2
/posts/post-2/3
Is that what you need?
Like mention #Aaron the problem is for double array of filter y el map.
return {
paths: [
{ params: { id: '1' } },
{ params: { id: '2' } }
],
fallback: ...
}
Doc 📚 ➡ https://nextjs.org/docs/basic-features/data-fetching#the-paths-key-required

Cannot read property 'columns' of undefined

I am trying to read json data from server and map. When I enter the same data with hand as a list to the code. It works. But when I am trying to read data from the server it does not work. I know problem is in mapping but I could not figure out. What can be the problem? This is code and json data. Thanks
class App extends Component {
constructor(props) {
super(props);
this.state = {
boards: {
id: null,
name: null,
owner: null,
columns:[]
}
};
}
getBoard() {
fetch("http://localhost:3001/boards/2")
.then(res => res.json())
.then(list => console.log(list))
.then(list => this.setState({boards: list}));
}
componentWillMount() {
this.getBoard();
}
{this.state.boards.columns.map((column, columnIndex) => (<Column
status={this.state.addModalShow}
onModalShow={this.onModalShow}
onHide={addModalClose}
addCard={this.addTask}
column={column}
columnIndex={columnIndex}
key={columnIndex}
onMoveLeft={cardIndex => this.handleMove(columnIndex, cardIndex, DIRECTION_LEFT)}
onMoveRight={cardIndex => this.handleMove(columnIndex, cardIndex, DIRECTION_RIGHT)}
onAddCard={() => this.handleAdd(columnIndex)}
deleteColumn={() => this.deleteColumn(columnIndex)}
addColumn={() => this.handleAdd()}
deleteTask={cardIndex => this.deleteTask(columnIndex, cardIndex)}/>))}
{
id: 2,
name: "Board3",
owner: "Ali",
-columns: [
-{
id: 5,
name: "eee",
cards: [
-{
id: 5,
name: "TestA",
description: "Desc",
link: "google.com",
deadline: "2013-04-06"
},
-{
id: 8,
name: "testB",
description: "Desc",
link: "google.com",
deadline: null
}
]
},
-{
id: 6,
name: "ff",
cards: []
}
]
}
But you don't return anything inside the function that prints the response to the console. Please read about Promise chaining.
Either return list in your second 'then' block or remove it completely.

Sequelize - After findAll, delete with a single query

I have a table with an associated table. I am using beforeDestroy to remove any associated records up deletion.
Model.beforeDestroy(async (category: any) => {
const items = await Category.findAll({
where: {
category_id: category.id,
},
attributes: ['id'],
raw: true,
});
console.log(items); // [ { id: 2 }, { id: 3364 }, { id: 3365 } ]
items.map((item: any) => {
Category.destroy({ where: { id: item.id } });
});
});
}
I am trying to delete the matching items with a single destroy query rather than mapping through.
try:
Category.destroy({ where: { id:items.map(item=>item.id)} });

Categories