Home
Support Forums

queryStringParameters not triggering component re-render

Hello, everyone.
I’m using the token-hider template for my React francophone news SPA. When the component that contains the news article cards mounts, it uses the default state from Context to pull stories from all French-speaking countries. However, when a user clicks on one of the countries listed in the navbar, the country state updates as it should, but the news article cards remain the same, so there is no visible re-render. The endpoint to pull data from a specific country requires an additional countries parameter, so I suspect I am not using queryStringParameters correctly. Does anyone have any suggestions for how I can fix this issue?
Please let me know if I need to clarify anything. Thank you in advance for your help.

media-api.js

const process = require('process');

const axios = require('axios');

const qs = require('qs');

const handler = async (event) => {
  const country = qs.stringify(event.queryStringParameters);
  console.log('API_PARAMS', country);

  const { REACT_APP_API_KEY } = process.env;
  const URL = `http://api.mediastack.com/v1/news?access_key=${REACT_APP_API_KEY}&languages=fr` || `http://api.mediastack.com/v1/news?access_key=${REACT_APP_API_KEY}&languages=fr&countries=${country}`;

  try {
    const { data } = await axios.get(URL);
    return {
      statusCode: 200,
      body: JSON.stringify(data),
    };
  } catch (error) {
    const {
      status, statusText, headers, data,
    } = error.response;
    return {
      statusCode: error.response.status,
      body: JSON.stringify({
        status, statusText, headers, data,
      }),
    };
  }
};

module.exports = { handler };

CountryContext.js

import React, { useState, createContext } from 'react';
import PropTypes from 'prop-types';

export const CountryContext = createContext();

export const CountryProvider = ({ children }) => {
  const [country, setCountry] = useState('/.netlify/functions/media-api');


  const handleSelect = (e) => {
    setCountry(e);
    window.scrollTo({
      top: 0,
      behavior: 'smooth',
    });
  };

  return (
    <CountryContext.Provider value={{
      country,
      handleSelect,
    }}
    >
      {children}
    </CountryContext.Provider>
  );
};

CountryProvider.propTypes = {
  children: PropTypes.node.isRequired,
};

CountrySelector.js

import React, { useContext } from 'react';
import { Navbar, Nav } from 'react-bootstrap';
import { CountryContext } from '../context/CountryContext';

const CountrySelector = () => {
  const countryContext = useContext(CountryContext);
  const { handleSelect } = countryContext;

  const be = 'be';
  const fr = 'fr';
  const ma = 'ma';
  const ch = 'ch';

  return (
    <Navbar collapseOnSelect expand="lg" fixed="top" className="navbar nav-background" onSelect={handleSelect}>
      <Navbar.Brand className="font-nav-brand pl-2">Actuali-toute</Navbar.Brand>
      <Navbar.Toggle aria-controls="responsive-navbar-nav" />
      <Navbar.Collapse id="responsive-navbar-nav" className="justify-content-center font-nav-link">
        <Nav>
          <Nav.Link className="px-5" eventKey="/.netlify/functions/media-api">Francophonie</Nav.Link>
          <Nav.Link className="px-5" eventKey={`/.netlify/functions/media-api?country=${be}`}>Belgique</Nav.Link>
          <Nav.Link className="px-5" eventKey={`/.netlify/functions/media-api?country=${fr}`}>France</Nav.Link>
          <Nav.Link className="px-5" eventKey={`/.netlify/functions/media-api?country=${ma}`}>Maroc</Nav.Link>
          <Nav.Link className="px-5" eventKey={`/.netlify/functions/media-api?country=${ch}`}>Suisse</Nav.Link>
        </Nav>
      </Navbar.Collapse>
    </Navbar>
  );
};

export default CountrySelector;

In Netlify functions, queryStringParameters are used like this: event.queryStringParameters.foo where .foo would be the name of the parameter.

So, if your URL is https://www.domain.tld/.netlify/functions/getData/?bar=xyz&blah=abc, you’d get queryStringParameters as a JavaScript object, so console.log(event.queryStringParameters) would give the following output:

{
  bar: xyz,
  blah: abc
}

So you could get the required one using: event.queryStringParameters.bar.

Thank you, @hrishikesh! That fixed the issue for me. :slight_smile:
For anyone who comes upon this thread in the future, here’s how I changed my Function file:

const process = require('process');

const axios = require('axios');

const handler = async (event) => {
  const country = event.queryStringParameters.country || '';

  const { REACT_APP_API_KEY } = process.env;
  const URL = `http://api.mediastack.com/v1/news?access_key=${REACT_APP_API_KEY}&languages=fr&countries=${country}`;

  try {
    const { data } = await axios.get(URL);
    return {
      statusCode: 200,
      body: JSON.stringify(data),
    };
  } catch (error) {
    const {
      status, statusText, headers, data,
    } = error.response;
    return {
      statusCode: error.response.status,
      body: JSON.stringify({
        status, statusText, headers, data,
      }),
    };
  }
};

module.exports = { handler };