Ad

Pass Two Variables Into GraphQL Query, One From ReactComponentProps, Other Constructed From First One

- 1 answer

I am trying to pass two variables into the following GraphQL query.

import gql from "graphql-tag";

import { TypedQuery } from "../../core/queries";
import { Article, ArticleVariables } from "./types/Article";

const articleQuery = gql`
  query Article($slug: String!, $slugimg: String!) {
    pageBy(uri: $slug) {
      id
      pageId
      title
      date
      uri
      content(format: RENDERED)
      excerpt
    }
    mediaItemBy(slug: $slugimg) {
      uri
      sourceUrl
    }
  }
`;

export const TypedArticleQuery = TypedQuery<Article, ArticleVariables>(
  articleQuery
);

using the following code


type ViewProps = RouteComponentProps<{ slug: string }>;

export const View: React.FC<ViewProps> = ({
  match: {
    params: { slug },
  },
}) => (
  <TypedArticleQuery loaderFull variables={{ slug, slugimg }} errorPolicy="all">
    {({ data }) => {

Is there any way to create a new slugimg variable constructed from the slug variable coming from RouteComponentProps

for example, if the slug variable has value "about-us", then I need the slugimg to have value "about-us-img"

What is the most elegant way of doing this?

Thank you!

Ad

Answer

I believe you can do something like this

<TypedArticleQuery loaderFull variables={{ slug, slugimg:slug ==='about-us'?'about-us-img:'' }} errorPolicy="all">

You didn't state what you wish the value to be when it's not 'about-us' so you can substitute '' with slug or whatever you prefer

Ad
source: stackoverflow.com
Ad