Home > Mobile >  How to fetch array data from url in react?
How to fetch array data from url in react?

Time:06-11

I want to fetch data from url in react.

There is data below:

{"data":[
{"id":"3",
"type":"blocks",
"attributes":{
    "index":1,
    "data":"The Human Torch",
},
{"id":"4",
"type":"blocks",
"attributes":{
    "index":2,
    "data":"is denied",
},
{"id":"5",
"type":"blocks",
"attributes":{
    "index":3,
    "data":"a bank loan",
}
]}

Here is my code:

screen.tsx:

function App: React.FunctionComponent = ( ) => {    
  const [blocks, setBlocks] = useState({
    blocks: []
  });

  const getBlockData = async () => {
    const response = await fetch( `${some.url}/blocks` ).then((response) => response.json());
    setBlocks(response);
  };

  useEffect(() => {
    getBlockData();
  }, []);

  return (
    <div className="app">
      { blocks.map((block: BlockType) => (
          <div className="content">
            Id:{block.id} 
            <div>
              Type:{block.type}
              Index:{block.attributes.index}
              Data:{block.attributes.data}
            </div>
          </div>
      ))}
    </div> 
  );
};

Block.ts:

export interface BlockType {
  id: string;
  type: string;
  attributes: {
    index: string;
    data: string;
  };
}

I run code but error issue.

error issue:

TypeScript error in : Property 'map' does not exist on type '{ blocks: never[]; }'. TS2339

133 |           <div className="app">

134 | { blocks.map((block: BlockType) => ( | ^ 135 | 136 | Id:{block.id} 137 | enter image description here What is my error and how to solve it? Who can help me? Thank you.

CodePudding user response:

.map() is a function for arrays, not objects. And blocks is an object:

const [blocks, setBlocks] = useState({
  blocks: []
});

Either call .map() on the array (which is a property on your object):

blocks.blocks.map(...)

Or change your object to just the array you want it to be:

const [blocks, setBlocks] = useState([]);

Edit: The data you're showing also doesn't match your object or array at all. The data you're showing is itself an object with a property on it called data, and that property is an array. So even once you correct the error, you're just going to have another error.

Define your object to match the structure you expect:

const [blocks, setBlocks] = useState({
  data: []
});

And iterate over the array property on the object:

blocks.data.map(...)

Basically:

  1. Keep your data structures consistent.
  2. Know which of your data structures are objects and which are arrays.
  • Related