0

I'm building this news website which takes input the news topic (that the user wants to see), fetches data from an api and renders them. But when I dispatch the action, the user inputted topic doesn't reach searchBlog.js. See below for clarity.

All the import/export works fine, I've tested them.

The SearchBar component from where the action is called

function SearchBar() {
    const classes = useStyles();
    const [search, setSearch] = useState('farmer');

    const handleChange = e => {
        setSearch(e.target.value);
    };

    const handleSubmit = e => {
        e.preventDefault();
        searchBlogs(search);
    };

    return (
        <Paper
            component="form"
            className={classes.root}
            onSubmit={handleSubmit}
        >
            <InputBase
                className={classes.input}
                placeholder="Type your search"
                inputProps={{ 'aria-label': 'type your search' }}
                onChange={handleChange}
            />
            <IconButton
                type="submit"
                className={classes.iconButton}
                aria-label="search"
            >
                <SearchOutlined />
            </IconButton>
        </Paper>
    );
}

searchBlogs.js - action that needs to work but doesn't

export const searchBlogs = query => async dispatch => {
    console.log(query);   // This line never prints
    dispatch({ type: SEARCH_BLOGS, payload: query });

    try {
        const data = await fetchNews(query);
        dispatch({ type: UPDATE_BLOGS, payload: data });
    } catch (err) {
        dispatch({ type: SEARCH_FAIL, payload: err.message });
    }
};

But if I remove the thunk feature (async dispatch callback)

export const searchBlogs = query => {
    console.log(query);  // It prints now
    ...
}

fetchNews.js - If this helps

export const fetchNews = query =>
    axios.get(URL + `q=${query}&apiKey=${process.env.REACT_APP_NEWS_API}`);

I don't understand the error here. Is it something related to not handling the async call correctly? Any help would be appreciated.

Major_Ash
  • 199
  • 3
  • 16

3 Answers3

1

You're not dispatching the action.

import { useDispatch } from 'react-redux'

function SearchBar() {
  const dispatch = useDispatch()
  const [search, setSearch] = useState('farmer')

  const handleSubmit = (e) => {
    e.preventDefault()
    dispatch(searchBlogs(search))
  }

  // rest of the code
}
Arun Kumar Mohan
  • 11,517
  • 3
  • 23
  • 44
1

Use connect() function connects a React component to a Redux store.

export default connect(null, { searchBlogs } )(SearchBar);

Then you need to get action from component props something like this:

function SearchBar({searchBlogs}) {
    const classes = useStyles();
    const [search, setSearch] = useState('farmer');

    const handleChange = e => {
        setSearch(e.target.value);
    };

    const handleSubmit = e => {
        e.preventDefault();
        searchBlogs(search);
    };

    return (
        <Paper
            component="form"
            className={classes.root}
            onSubmit={handleSubmit}
        >
            <InputBase
                className={classes.input}
                placeholder="Type your search"
                inputProps={{ 'aria-label': 'type your search' }}
                onChange={handleChange}
            />
            <IconButton
                type="submit"
                className={classes.iconButton}
                aria-label="search"
            >
                <SearchOutlined />
            </IconButton>
        </Paper>
    );
}
Chellappan வ
  • 23,645
  • 3
  • 29
  • 60
-1

You're getting this issue due to the fact you are calling an Asynchronous Function inside a Synchronous Function.

An immediate fix is to ammend your handleSubmit method:

const handleSubmit = async e => {
    e.preventDefault();
    // console.log(search)  => This line works so search is non-empty
    await searchBlogs(search);
};

However I'd also highly recommend you read the following related question: Call An Asynchronous Javascript Function Synchronously

Lachlan Young
  • 1,266
  • 13
  • 15