Slyds
Slyds

Reputation: 45

Pass two variables into GraphQL query, one from ReactComponentProps, other constructed from first one

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!

Upvotes: 0

Views: 285

Answers (2)

Jerome
Jerome

Reputation: 2761

more generic assuming you want to add -img to any slug value

    export const View: React.FC<ViewProps> = 
({ match: { params: { slug }, }, }) => 
{ const slugimg = ` ${slug}-img` ;
return ( <TypedArticleQuery loaderFull variables={{ slug, slugimg }} errorPolicy="all"> {({ data }) => { –

Upvotes: 0

Damian Green
Damian Green

Reputation: 7495

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

Upvotes: 1

Related Questions