Link to home
Start Free TrialLog in
Avatar of jblayney
jblayneyFlag for Canada

asked on

React / JSON error TypeError: pages is undefined

pages.json
Hello,
Still struggling with JSON, json file attached and linked above

the error  i get is

TypeError: pages is undefined
FetchContent
src/Components/Pages/Page.js:33

I am also trying to get a single result that matches the pageID  that is sent


  30 | 
  31 | return (
  32 | 
> 33 |    <div>
     | ^  34 |    {pages.map(page => (
  35 |         <h1 key={page.id}>{page.title.rendered}</h1>
  36 |        ))}

Open in new window


my code

function FetchContent( { pageId } ) {
    

    const [pages, setPages] = useState([]); 
  
     useEffect(() => {
        fetch("pages.json?id={pageId}" ,{
      headers : { 
        'Content-Type': 'application/json',
        'Accept': 'application/json'
       }
    })
        .then(res => res.json())
    
        .then(json =>{
             setPages(json.items)}
              )
         });
    
    
    
    return (
    
        <div>
        {pages.map(page => (
         <h1 key={page.id}>{page.title.rendered}</h1>
        ))}

        </div>

        
    );
    
    
}

Open in new window


Avatar of HainKurt
HainKurt
Flag of Canada image

what PageID are you using?
User generated image
Avatar of jblayney

ASKER

2797 to start...

I have some issue with my menu IDs matchig page ID, but for testing purposes now the pageId is 2797
are you sure about this line

fetch("pages.json?id={pageId}" ,{ 

pages.json is just a text file, and it does not do anything if you pass an id here...
did you get this code from somewhere or you wrote?

ok I got rid of the error

I changed this

.then(json =>{
             setPages(json.items)}
              )
         });

Open in new window


   to
.then(json =>{
             setPages(json)}
              )
         });

Open in new window

But is is still grabbing eveything,
Hello,

"are you sure about this line"
I am not sure about that line, I found it online

If it is locally hosted the load time should not be an issue so I could fetch it all and try this, it is giving an unexpected token error, something wrong with my syntax

{pages.map(page => (
        
        if(  {page.id} === { pageId }) {
            <h1 key={page.id}>{page.title.rendered}</h1>
        } else {
            <h1>Page Not Found</h1>    
        }
        
        ))}

Open in new window



not sure, but looks like, you have to find the page by ID first
set it to page
then use it

a lookup function
// Find array element which has a key value of val 
function find (arr, key, val) {
  for (var ai, i = arr.length; i--;)
    if ((ai = arr[i]) && ai[key] == val) return ai;
  return null;
};

Open in new window


const [page, setPage] = useState([]);

useEffect(() => {
        fetch("pages.json" ,{ ... }
        .then(res => res.json())
        .then(json =>{
             setPage(find (json, 'id', '{pageId}'))
             })
});
...

Open in new window

I don't know if i matters whether I fetch I single array result (probably better), or just conditionally display the one I want


the error

./src/Components/Pages/Page.js
SyntaxError: /Users/justin/Desktop/react-wordpress-headless/src/Components/Pages/Page.js: Unexpected token (34:3)

  32 |       {pages.map(page => ( (
  33 |       
> 34 |          if ( {page.id} === { pageId } ) {
     |          ^
  35 |             <h1 key={page.id}>{page.title.rendered}</h1>
  36 |          }   

Open in new window

the conditional code

return (
        
        
        <>
    
        {pages.map(page => ( 
        
            if ( {page.id} === { pageId } ) {
                <h1 key={page.id}>{page.title.rendered}</h1>
            } 
        
        ))}

        </>
        
        
    );
    

Open in new window



thank you for that, it seems close

it doesn't find any results

TypeError: pages is null

Open in new window


I adjusted your syntax a bit too


function find (arr, key, val) { // Find array element which has a key value of val 
  for (var ai, i = arr.length; i--;)
    if ((ai = arr[i]) && ai[key] == val)
      return ai;
  return null;
};

function FetchContent( { pageId } ) {
    
const [pages, setPages] = useState([]); 
  
     useEffect(() => {
        fetch("pages.json" ,{
      headers : { 
        'Content-Type': 'application/json',
        'Accept': 'application/json'
       }
    })
        .then(res => res.json())
        
        .then(json =>{
             setPages(find (json, 'id', {pageId}))}
              )
         });
    
    
    
    return (
        
        
        <>
    
        {pages.map(page => ( 

                <h1 key={page.id}>{page.title.rendered}</h1>
            
        ))}

        </>
        
        
    );
    
    
}

Open in new window

no pages, use page, setPage
const [page, setPage] = useState([]); 
...
setPage(find (json, 'id', {pageId}))}

Open in new window

and remove Line 33 and 37, we will have only page
That makes no difference, before in my map  (which worked by showing all results)  I had so it needed to match is all

       {pages.map(page => (

                <h1 key={page.id}>{page.title.rendered}</h1>
           
        ))}

I changed it to singular, I still get page is null error
I am thinking, you should just use

<h1 key={page.id}>{page.title.rendered}</h1> 

no pages... we will have only page, set after getting the json, and filtered by id
I did rewrite it, but just to confirm it still returns the error and no results

can I see latest code

function FetchContent( { pageId } ) {
    
const [page, setPage] = useState([]); 
  
     useEffect(() => {
        fetch("pages.json" ,{
      headers : { 
        'Content-Type': 'application/json',
        'Accept': 'application/json'
       }
    })
        .then(res => res.json())
        
        .then(json =>{
             setPage(find (json, 'id', {pageId}))}
              )
         });
    
    
    
    return (
        
        
        <>
    
        {page.map(page => ( 
                 
                <h1 key={page.id}>{page.title.rendered}</h1>
            
        ))}

        </>
        
        
    );
    
    
}

Open in new window

just remove Line 26 and 30...
does it work that way?

Hello,

No i get a TypeError: page.title is undefined error
what happens if you use

this.page.id
this.page.title.rendered
no difference, it isnt matching a result
is it complainin about page.title but not page.id?
does this work?

<h1 key={page.id}>{page.modified}</h1> 
no differnce..

im 100% sure the error is that it is not finding a result
is there any console error, is find function working fine?
https://jsfiddle.net/HainKurt/t36dvabu/
tons of console errors

Warning: Each child in a list should have a unique "key" prop. Check the render method of `MyRoutes`. See https://reactjs.org/link/warning-keys for more information. MyRoutes@http://localhost:3000/react-wordpress-headless/static/js/main.chunk.js:63:81 div Router@http://localhost:3000/react-wordpress-headless/static/js/0.chunk.js:35747:30 BrowserRouter@http://localhost:3000/react-wordpress-headless/static/js/0.chunk.js:35367:35 App@http://localhost:3000/react-wordpress-headless/static/js/main.chunk.js:93:1 index.js:1

Uncaught TypeError: page is null    FetchContent Page.js:41
    React 12
    unstable_runWithPriority scheduler.development.js:646
    React 5
    FetchContent Page.js:33
Page.js:41

The above error occurred in the <FetchContent> component: FetchContent@http://localhost:3000/react-wordpress-headless/static/js/main.chunk.js:654:1 div Page@http://localhost:3000/react-wordpress-headless/static/js/main.chunk.js:694:75 Route@http://localhost:3000/react-wordpress-headless/static/js/0.chunk.js:36112:29 MyRoutes@http://localhost:3000/react-wordpress-headless/static/js/main.chunk.js:63:81 div Router@http://localhost:3000/react-wordpress-headless/static/js/0.chunk.js:35747:30 BrowserRouter@http://localhost:3000/react-wordpress-headless/static/js/0.chunk.js:35367:35 App@http://localhost:3000/react-wordpress-headless/static/js/main.chunk.js:93:1 Consider adding an error boundary to your tree to customize error handling behavior. Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries. index.js:1

Uncaught (in promise) TypeError: page is null    FetchContent Page.js:41
    React 12
    unstable_runWithPriority scheduler.development.js:646
    React 5
    FetchContent Page.js:33
Page.js:41

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function. Nav@http://localhost:3000/react-wordpress-headless/static/js/main.chunk.js:441:83 div div div header Header@http://localhost:3000/react-wordpress-headless/static/js/main.chunk.js:490:1 div Router@http://localhost:3000/react-wordpress-headless/static/js/0.chunk.js:35747:30 BrowserRouter@http://localhost:3000/react-wordpress-headless/static/js/0.chunk.js:35367:35 App@http://localhost:3000/react-wordpress-headless/static/js/main.chunk.js:93:1 index.js:1

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function. FetchContent@http://localhost:3000/react-wordpress-headless/static/js/main.chunk.js:654:1 div Page@http://localhost:3000/react-wordpress-headless/static/js/main.chunk.js:694:75 Route@http://localhost:3000/react-wordpress-headless/static/js/0.chunk.js:36112:29 MyRoutes@http://localhost:3000/react-wordpress-headless/static/js/main.chunk.js:63:81 div Router@http://localhost:3000/react-wordpress-headless/static/js/0.chunk.js:35747:30 BrowserRouter@http://localhost:3000/react-wordpress-headless/static/js/0.chunk.js:35367:35 App@http://localhost:3000/react-wordpress-headless/static/js/main.chunk.js:93:1 index.js:1

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function. MyRoutes@http://localhost:3000/react-wordpress-headless/static/js/main.chunk.js:63:81 div Router@http://localhost:3000/react-wordpress-headless/static/js/0.chunk.js:35747:30 BrowserRouter@http://localhost:3000/react-wordpress-headless/static/js/0.chunk.js:35367:35 App@http://localhost:3000/react-wordpress-headless/static/js/main.chunk.js:93:1 index.js:1







Open in new window


Line 15, if we hard code the page, does it work

setPage(find (json, 'id', {pageId}))} 

>>>

setPage({id:2927, title:"test page"})
} 

a different error

TypeError: page.map is not a function

I really appreacite the help, I get the impression you are a javascript programmer and you are experimenting in react

If I go back to this
.then(json =>{
             setPage(json)
     
      }

it dumps all 10 records from the JSON
Hello,

I found something online which is giving me a result, but the result isnt changing


function FetchContent( { pageId } ) {
    
const [page, setPage] = useState([]); 

     useEffect(() => {
      fetch("pages.json" ,{
      headers : { 
        'Content-Type': 'application/json',
        'Accept': 'application/json'
       }
    })
        .then(res => res.json())
        .then(json =>{
             setPage(json)
      
                      }
              )
         });
    
    const found = page.find(id => id = { pageId });
    
    if (!found) return <div />;
    return (
        <>
        
             <h1 key={found.id}>{found.title.rendered}</h1>
        

        </>
    );
}


Open in new window

It is just returning

3739 no matter pageID i send it


is it possible to create a fiddle
like this one...

we hardcode the json and see whats going on...
https://jsfiddle.net/HainKurt/4e63cbw0/

I have code sandbox

https://codesandbox.io/live/7gu09fv

the page we are wroking on is Components / Pages / Page.js
ASKER CERTIFIED SOLUTION
Avatar of jblayney
jblayney
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial