DEV Community

Cover image for My freelancing experience with Laravel + GraphQL Part 2: How to use Query/Mutation in frontend with React.js
尤川豪
尤川豪

Posted on

My freelancing experience with Laravel + GraphQL Part 2: How to use Query/Mutation in frontend with React.js

In the previous article, I introduced the strength of GraphQL and how to implement it in Laravel

Let's talk about how to use it in frontend with React.js today!

Example project and API playground

I implemented an e-commerce sample project with graphql + laravel in the previous post

https://graphql-laravel-example.tw/graphiql

I created a simple e-commerce frontend with Next.js this time

https://graphql-react-example.vercel.app/

You can browse products & subscribe the newsletter in the web app!


For graphql query sample code:

https://github.com/howtomakeaturn/graphql-react-example/blob/main/app/page.js

For graphql mutation sample code:

https://github.com/howtomakeaturn/graphql-react-example/blob/main/app/newsletter.js

I use the native fetch function to call graphql api, so you should be able to do it with any http libraries.

And I use swr library (Next.js official library) as state manager, but any state manager should be fine.

Strengths

The best part about graphql is frontend devs can decide what data should be returned!

Frontend devs can try & see the results with the powerful graphql playground

https://graphql-laravel-example.tw/graphiql

Even relational data can be returned easily!

const gql = `query {
  products {
    id
    name
    description
    featured_image
    price
    comments {
      content
      user {
        name
      }
    }
  },
}`;
Enter fullscreen mode Exit fullscreen mode

It reduces devlopment time and communication time a lot!

Source code

React source code

https://github.com/howtomakeaturn/graphql-react-example

Laravel backend sample project

https://graphql-laravel-example.tw/

Laravel backend source code

https://github.com/howtomakeaturn/graphql-laravel-example

Conclusions

With the above example projects,

You should be able to implement your own graphql APIs in your project!

I will realease more sample code in the following articles, you should definitely give graphql a try!

(This is series article. More content will be released soon.)

Top comments (0)