Notion column_list empty columns - json

Building a Nextjs app with Notion as Headless CMS.
When i fetch the blocks, all of them work good except column_list, which renders the column children but not getting their content.
This is how i render the blocks:
export const getBlocks = async (blockId: string) => {
const blocks = [];
let cursor;
while (true) {
const { results, next_cursor }: any = await notion.blocks.children.list({
start_cursor: cursor,
block_id: blockId,
});
blocks.push(...results);
if (!next_cursor) {
break;
}
cursor = next_cursor;
}
return blocks;
};
... and then in getStaticProps i do this:
export const getStaticProps = async (context: any) => {
const { id } = context.params;
const blocks = await getBlocks(id);
// Retrieve block children for nested blocks (one level deep), for example toggle blocks
// https://developers.notion.com/docs/working-with-page-content#reading-nested-blocks
const childBlocks = await Promise.all(
blocks
.filter((block: any) => block.has_children)
.map(async (block: any) => {
return {
id: block.id,
children: await getBlocks(block.id),
};
})
);
const blocksWithChildren = blocks.map((block: any) => {
// Add child blocks if the block should contain children but none exists
if (block.has_children && !block[block.type].children) {
block[block.type]["children"] = childBlocks.find(
(x: any) => x.id === block.id
)?.children;
}
return block;
});
return {
props: {
blocks: blocksWithChildren,
},
revalidate: 1,
};
};
...so when i console.log("BLOCKSSS", blocks); i get this:
As you see the column:{} is empty even thought i have content on those 2 columns:
Any help would be appreciated!

Related

NextJS get custom JSON depending on page

I know you can do the following
export async function getStaticProps({ params }) {
console.log(params)
const res = await fetch(`https://example.com/api-access/news/2021_autumn_home_style_tips`)
const data = await res.json()
if (!data) {
return {
notFound: true,
}
}
return {
props: { data }, // will be passed to the page component as props
}
}
however what if the last part depending on the news item a user presses needs to change.
https://example.com/api-access/news/2021_autumn_home_style_tips
https://example.com/api-access/news/2020_autumn_home_style_tips
https://example.com/api-access/news/2021_car
https://example.com/api-access/news/top_songs
How can I make a [slug].js page that allows me to run that slug url for example
https://myexample.com/news/top_songs
would fetch data from https://example.com/api-access/news/top_songs
I have tried
export const getStaticPaths: GetStaticPaths<{ slug: string }> = async () => {
console.log(params)
const res = await fetch('https://example.com/api-access/news/{slug}')
const data = await res.json()
if (!data) {
return {
notFound: true,
}
}
return {
props: { data }, // will be passed to the page component as props
}
}
But get this error

Data fetch from JSON file

I am trying to fetch data from external JSON and I was able to console.log it, so the fetch works, but I am having trouble to print the values.
JSON:
{
"data": {
"shoes": [
{
"types": [
{
"color": "pink",
}]
}]
}
I need to get access to the color (pink).
This is my fetch:
const shoesInformations = "json.url"
const [shoesData, setShoesData] = useState([]);
useEffect(() => {
getShoesInfo();
}, []);
const getShoesInfo = async () => {
try {
const response = await fetch(shoesInformations);
const jsonData = await response.json();
const { data } = jsonData;
setShoesData(jsonData);
console.log(data);
} catch (err) {
console.log(err);
}
};
And my attempt to print it:
<p>{shoesData.types.color}</p>
I do not need to map through the data just print the value one by one {shoesData.types.color[1]}
The main problem is that you assign the whole fetch response instead of only the shoes array within it to the shoesData state variable. Try this:
const [shoesData, setShoesData] = useState([]);
useEffect(() => {
getShoesInfo();
}, [getShoesInfo]);
const getShoesInfo = async () => {
try {
const response = await fetch(shoesInformations);
const jsonData = await response.json();
setShoesData(jsonData.data.shoes);
} catch (err) {
console.log(err);
}
};
and then when you want to present it first add a check for empty array or use the safe navigation operator. Either do (if you really want it hardcoded):
<p>{shoesData[0]?.types[0].color}</p>
<p>{shoesData[1]?.types[0].color}</p>
or more flexibly something like:
const getShoesRepresentation = () => {
if (shoesData.length > 0) {
return null;
}
else {
return (
<p>{shoesData[0].types[0].color}</p>
);
}
};
and then use {getShoesRepresentation()} in your rendering. This will handle the empty array case and you can extend it to handle iteration over all shoe objects that you need. I strongly suggest you use an iteration approach instead of hard-coding the data like that. You can safely use it by supplying shoeIndexes which contains only the indexes you want to present and then iterate over them and create a respective <p> for each.
shoesData.types.color[1] won't work, you only have 1 element, so your index must be 0:
shoesData.types.color[0]

How could I pass JSON object array result to my api URL? (In REACT)

I have to fetch 2 api from backend, and try to get the result from this two. but, at the moment, the JSON result I get from the first API is object Array in JSON. I need to pass the id from first API(using setState) to second API for path variables. But when I do in my way, it fail to retrieve the data. Consider the code below:
componentDidMount(){
// console.log(loginEmail)
fetch(`http://localhost:9000/api/item/list`,)
.then((resp)=>{
resp.json().then((res)=>{
console.log(res.data);
// localStorage.setItem('id', res.data.user_info.id);
this.setState({data: res.data});
}
)
})
const id = this.state.data.id;
fetch(`http://localhost:9000/api/item/photo/view/${id}`,)
.then((resp)=>{
resp.json().then((res)=>{
console.log(res);
// localStorage.setItem('id', res.data.user_info.id);
this.setState({res});}
)
})
}
The problem is that fetch returns a Promise so, at the line
const id = this.state.data.id;
You do not have data populated yet.
You have to concatenate the two requests in a way like the following:
componentDidMount() {
fetch(`http://localhost:9000/api/item/list`)
.then((resp) => {
// return the id
})
.then((id) => {
fetch(`http://localhost:9000/api/item/photo/view/${id}`)
.then((resp) => {
// do what you need with the result
})
})
}
Fetch is asynchronous, which means javascript will
fetch data on the first call with no waiting, and continue
to the second fetch call where the id is not defined or Null.
In order to fix that you can use promises as follow
My code example
import React from "react";
class Home extends React.Component {
constructor() {
super();
this.state = {
res: [],
}
}
// http://jsonplaceholder.typicode.com/users
fetchData(url) {
return new Promise((resolve, reject) => {
fetch(url)
.then((resp) => {
resp.json().then((res) => {
console.log(res);
// localStorage.setItem('id', res.data.user_info.id);
resolve(res);
}
)
})
})
}
async componentDidMount() {
let data = await this.fetchData("http://jsonplaceholder.typicode.com/users");
console.log("data :", data);
let id = data[0].id;
console.log("Id :", id);
let newData = await this.fetchData(`http://jsonplaceholder.typicode.com/users/${id}`);
this.setState({ res: newData });
}
render() {
return (
<div>
Call API
</div>
)
}
}
export default Home
Adapted on your code
fetchData(url) {
return new Promise((resolve, reject) => {
fetch(url)
.then((resp) => {
resp.json().then((res) => {
console.log(res.data);
// localStorage.setItem('id', res.data.user_info.id);
resolve(res.data);
}
)
})
})
}
async componentDidMount() {
// console.log(loginEmail)
let data = await this.fetchData("http://localhost:9000/api/item/list");
let id = data.id;
let newData = await this.fetchData(`http://localhost:9000/api/item/photo/view/${id}`);
this.setState({ res: newData });
}
You need to make sure that each id gets its relevant results.
async componentDidMount() {
await fetch(`http://localhost:9000/api/item/list`)
.then(async (resp) => {
let req_ = resp.map((item)=>{
return await fetch(`http://localhost:9000/api/item/photo/view/${item.id}`)
})
let result = Promise.all(req_)
console.log(result)
})
}

How to Fetch Json with React-Table library

the example to which I refer is the following:
https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/sub-components
I would like to fetch a json file and pass the elements of the latter into the table instead of generating them as in the previous example.
The instructions for making fetch are clear to me but I can't understand how to integrate them in the "makeData" file.
This is my "makeData" code:
import ReactDOM from 'react-dom';
const range = len => {
const arr = []
for (let i = 0; i < len; i++) {
arr.push(i)
}
return arr
}
const newPerson = () => {
fetch('http://localhost:5000/api/azienda')
.then(res => res.json())
// .then((rows) => {
// ReactDOM.render(this.makeData(rows), document.getElementById('root'));
// });
}
export default function makeData(...lens) {
const makeDataLevel = (depth = 0) => {
const len = lens[depth]
return range(len).map(d => {
return {
...newPerson(),
subRows: lens[depth + 1] ? makeDataLevel(depth + 1) : undefined,
}
})
}
return makeDataLevel()
}
For any advice I will thank you
Create an array in the constructor ,where the data will be stored , fetch the data from the serverlink and then put it in the table
constructor(props, context) {
super(props, context);
this.state = { items: []};
}
getList = () => {
fetch("http://localhost:5000/api/azienda")
.then(res => res.json())
.then(items => this.setState({ items }))
.catch(err => console.log(err));
};
componentDidMount() {
this.getList();
}

How to delete object in array?

I used componentDidUpdate and in it I put a shift method, which is used to delete an object from a JSON array and thereby re-render the displayed posts, but the shift method deletes the first object from the array independently in which the delete button on the post will I press? Is there any possibility, then, to bypass the deletion of the first element in favor of the one that is designated to be deleted?
componentDidUpdate(prevProps, prevState) {
const {posts} = this.props;
const indexPosts = posts.findIndex((post) => post.id === this.state.postId);
if(prevProps.posts !== posts){
this.handleData();
} else if (indexPosts !== -1)
{
this.informationAlert();
const log = posts.splice(indexPosts, 1);
console.log(log);
}
}
EDIT: Actions
export const deletedPost = (id) => (dispatch) => {
axios
.delete(`https://jsonplaceholder.typicode.com/posts/${id}`, id, {
headers: {
'Content-type': 'application/json'
}
})
.then((post) =>
dispatch({
type: DELETED_POST,
payload: post.data
})
)
.catch((err) => console.log(err));
};
import { FETCH_POSTS, NEW_POST, DELETED_POST, FETCH_COMMENTS, NEW_COMMENT } from '../actions/types';
const initialState = {
items: [],
item: {},
itemComent: [],
itemNewComment: {},
deletedPost: []
};
export default function (state = initialState, action) {
switch (action.type) {
case FETCH_POSTS:
return {
...state,
items: action.payload
};
case NEW_POST:
return {
...state,
item: action.payload
};
case DELETED_POST:
return {
...state,
deletedPost: action.payload
};
case FETCH_COMMENTS:
return {
...state,
itemComent: action.payload
}
case NEW_COMMENT:
return {
...state,
itemNewComment: action.payload
}
default:
return state;
}
}
EDIT 2:
const mapStateToProps = (state) => ({
posts: state.posts.items,
newPost: state.posts.item,
deletedPost2: state.posts.deletedPost
});
EDIT 3:
handleDeletedPost = (id) => {
this.setState({
postId: id
})
}
Edit 4:
//I added in constructor
this.state: dataPost: '',
//next I create function to load data and send to state dataPost
handleData = (e) => {
const {posts} = this.props;
const {dataPost} = this.state;
const letang = posts;
const postsData = dataPost;
if (postsData.length <= 0) {
this.setState({
dataPost: letang
})
} else {
console.log('stop')
}
}
// next i create in componentDidUpdate this code
componentDidUpdate(prevProps, prevState) {
const {posts} = this.props;
const indexPosts = posts.findIndex((post) => post.id === this.state.postId);
if(prevProps.posts !== posts){
this.handleData();
} else if (indexPosts !== -1)
{
this.informationAlert();
const log = posts.splice(indexPosts, 1);
console.log(log);
}
}
** When I added loop if (indexPosts !== -1) then my array is cut only one object :-)
API Posts: https://jsonplaceholder.typicode.com/posts/
The results are visible at this link when you press details and then the delete icon: https://scherlock90.github.io/api-post-task/
You need to use splice to delete an element from array.
In splice you need to provide startIndex and number of elements to remove in second argument. In below code find index using `findIndex method, second argument is 1 as we need to remove only 1 element.
Try this
componentDidUpdate (prevProps, prevState) {
if (prevProps.deletedPost) {
const { posts } = this.props
const letang = posts.splice(posts.findIndex( (post)=> post.id === prevProps.deletedPost.id), 1);
console.log(posts); // this should have array without deletedPost
}
}
This might help:
componentDidUpdate (prevProps, prevState) {
if (prevProps.deletedPost) {
const letang = this.props.posts;
letang.splice(deletedPost, 1);
}
}
the slice() takes the index of the object and an optional number of items to delete. since you just want to delete a single object you pass 1.
This might help, try filtering out the object you dont want in the array.
componentDidUpdate (prevProps, prevState) {
if (prevProps.deletedPost) {
const letang = this.props.items.filter(p => p.id !== prevProps.deletedPost.id);
}
}
UPDATED
I think you should be deleting the items in your redux store rather than trying to delete the posts from your api since the api might rather be generating the same data randomly. Change your actionCreator to
export const deletedPost = (id) => {
dispatch({
type: DELETED_POST,
payload: id
});
};
Then use this in your reducer so you can focus on items array coming from your reducer store. Then remove deletedPost: [] from your reducer.
...
case DELETED_POST:
const newItems = state.items.filter(p => p.id !== action.payload);
return {
...state,
items: [ ...newItems ],
};
...
use splice() to delete :), you can find the index of post which should be deleted and then delete it by using this method.