1

TL/DR: Having trouble referencing items in array by index (using React), could use some guidance.

I am attempting to create a component on my SPA out of data coming from an API. Using React hook useState and useEffect I have created state, done an axios call, and then set the response.data.articles to state (.articles is the array of objects I am using to create the dynamic content).

 function App() {

  const [storyArray, setStoryArray] = useState();

  useEffect(() => {
    axios.get('http://newsapi.org/v2/everything?domains=wsj.com&apiKey=[redacted_key_value]')
      .then((response) => { 
        // console.log(response);
        setStoryArray(response.data.articles);
      })
      .catch((err) => {
        console.log(err);
      })
  }, [])

  console.log(storyArray)

  return (
    <div className="App">
      <Directory />
      <HeaderStory />
    </div>
  );
}

From here, my state is an array of objects. My goal is to pass THE FIRST object as props to the component <HeaderStory /> but any time I attempt to reference this array item with dot notation I am met with an undefined error. My attempt at circumventing this is problem was to set the item to a variable and then pass the variable as props to the component.

const firstStory = storyArray[0];

This also resulted in an undefined error. Looking for advice / assistance on referencing items in an array to be passed and used in React.

2 Answers 2

2

On the first render the storyArray will have no value/undefined, The useEffect hook will execute only after component mount.

So you have to render the component conditionally, if the storyArray has value then only render the HeaderStory.

Example:

function App() {
    const [storyArray, setStoryArray] = useState();
    useEffect(() => {
        axios.get('http://newsapi.org/v2/everything?domains=wsj.com&apiKey=[redacted_key_value]')
            .then((response) => {
                // console.log(response);
                setStoryArray(response.data.articles);
            })
            .catch((err) => {
                console.log(err);
            })
    }, [])

    return (
        <div className="App" >
            <Directory />
            {storyArray && <HeaderStory firstStory={storyArray[0]} />}
        </div>
    );

}
Sign up to request clarification or add additional context in comments.

Comments

2

You should init default value for storyArray.

Example code:

function App() {

  const [storyArray, setStoryArray] = useState([]); //Init storyArray value

  useEffect(() => {
    axios.get('http://newsapi.org/v2/everything?domains=wsj.com&apiKey=[redacted_key_value]')
      .then((response) => { 
        // console.log(response);
        setStoryArray(response.data.articles);
      })
      .catch((err) => {
        console.log(err);
      })
  }, [])

  console.log(storyArray)

  return (
    <div className="App">
      <Directory />
      <HeaderStory firstStory={storyArray[0] || {}} />
    </div>
  );
}

I set props firstStory={storyArray[0] || {}} because if storyArray[0] is undefined then pass empty object "{}" for firstStory prop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.