2

I keep getting this reference error and no idea what is wrong.

ReferenceError: Cannot access 'search' before initialization App C:/Users/GS66/Desktop/IN20/IFN666/week4/src/App.js:60 57 | 58 | export default function App() { 59 |

60 | const { loading, headlines, error } = useNewsArticles(search); 61 | const [search, setSearch] = useState(""); 62 | 63 | if (loading) {

This is the App part in App.js

export default function App() {
const {loading, headlines, error} = useNewsArticles(search);
const [search, setSearch] = useState("");

if (loading) {
    return <p>Loading...</p>;
}
if (error) {
    return <p>Something went wrong: {error.message}</p>
}

return (
    <div className="App">
        <h1>News Headlines</h1>
        <SearchBar onSubmit={setSearch}/> {
            headlines.map((headline) => (
                //headline is now an object
                <Headline key={headline.url} title={headline.title}/>
            ))
        }
    </div>
);

}

And this is the useNewsArticles function part from api.js.

export function useNewsArticles(search) {
const [loading, setLoading] = useState(true);
const [headlines, setHeadlines] = useState([]);
const [error, setError] = useState(null);

useEffect(() => {
    (async() => {
        try {
            setHeadlines(await getHeadlines(search));
            setLoading(false);
        } catch (err) {
            setError(error);
            setLoading(false);
        }
    })();
}, [search]);

    return {
        loading,
        headlines,
        error,
    };

}
2
  • Not sure what to say because the error says it all: you are using search before you define it, which happens one line further down... The :60 in the error means line 60 so this way you know which line the error is talking about Commented Apr 25, 2021 at 8:24
  • You're using search in line 2. You initialize search in line 3. Commented Apr 25, 2021 at 8:24

2 Answers 2

3

You are initializing search in line 3 and using in line 2. You should do the reverse, like

const [search, setSearch] = useState("");
const {loading, headlines, error} = useNewsArticles(search);

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

Comments

1

This error appears when you're trying to use a variable before declaring it.

First declare search with useState() then use it as a hook param.

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.