Closed GiacomoSilli closed 5 years ago
Here's an example on how to use Algolia with React (InstantSearch): https://codesandbox.io/s/github/algolia/create-instantsearch-app/tree/templates/react-instantsearch
Thanks for answer, but i'm looking for an example with gatsby and maybe autocomplete
Frontend with Gatsby isn't really any different of any other implementation. @janosh made an autocomplete / gatsby implementation here you can look at : https://github.com/janosh/ocean-artup
Personally I find many differences, without using gatsby I took 10 minutes to implement algolia, with gatsby continue to have problems, unfortunately I find some difficulties.
I'm also trying to run locally ocean-artup blog https://github.com/janosh/ocean-artup but I get the following error:
error UNHANDLED REJECTION
Error: Cannot query field "allContentfulPage" on type "Query". Did you mean "allSitePage" or "allContentfulContentType"?
GraphQL request (3:5)
2: {
3: content: allContentfulPage {
^
4: edges {
- gatsby-node.js:39 pageSets.forEach
C:/Users/***/Documents/REACT/ocean-artup/gatsby-node.js:39:32
- next_tick.js:189 process._tickCallback
internal/process/next_tick.js:189:7
I also followed the @janosh https://janosh.io/blog/gatsby-algolia-search guide, but there are many errors and it is not complete
@GiacomoSilli The repo won't be able to compile locally until you supply the environment variables listed in .env.example
:
# rename this file to .env and supply the listed values
# also make sure they are available to the build tool (e.g. netlify)
# warning: variables prexifed with GATSBY_ will be made available to client-side code,
# be careful not to expose sensitive data
GATSBY_ALGOLIA_APP_ID=insertValue
GATSBY_ALGOLIA_SEARCH_KEY=insertValue
ALGOLIA_ADMIN_KEY=insertValue
CONTENTFUL_SPACE_ID=insertValue
CONTENTFUL_ACCESS_TOKEN=insertValue
GA_TRACKING_ID=insertValue
Regarding the blog post, I'd be very interested to hear how you think I might improve it. If you have specific questions, I'm happy to help with those.
Hello, thanks for the reply. Of course, I filled out those fields by entering them directly in gatsby-config or by editing .env.example.
Initially it returned me "invalid token". After configuring contentful and algolia, I no longer receive the token error but the one I wrote in the previous post, something about the query.
About this query, I do not know how to solve it, I'm still inexperienced with gatsby, and I do not know if it refers to contentful or algolia.
success open and validate gatsby-configs - 0.010 s
success load plugins - 0.275 s
success onPreInit - 1,476 s
success delete html and css files from previous builds - 0.010 s
success initialize cache - 0.035 s
success copy gatsby files - 0.192 s
success onPreBootstrap - 0.012 s
⠂ source and transform nodesStarting to fetch data from Contentful
Local default fetching
⢀ source and transform nodesdefault locale is: en-US
⠂ source and transform nodescontentTypes fetched 3
Updated entries 0
Deleted entries 0
Updated assets 0
Deleted assets 0
Fetch Contentful data: 483.134ms
success source and transform nodes - 0.569 s
success building scheme - 0.202 s
success createPages - 0.020 s
error UNHANDLED REJECTION
Error: Can not query the "allContentfulPage" on type "Query" field. Did you mean "allSitePage" or "allContentfulContentType"?
GraphQL request (3: 5)
2: {
3: content: allContentfulPage {
^
4: edges {
As for the blog post we are missing steps, I had trouble understanding them, but I probably did not understand them completely ..
In the file
// src / components / Search / index.js
There are folders and styles which you do not explain in the guide
import Input from './Input'
import * as hitComps from './hits'
Then create a file with the style, but do not give it a name and explain where to insert it:
import styled, { css } from 'styled-components'
import { Search } from 'styled-icons/fa-solid/Search'
import Input from './SearchBox'
export const Root = styled.div`
position: relative;
display: grid;
grid-gap: 1em;
`
....
Then create the file:
// src / components / Search / SearchBox.js
New problem about this "./styles":
import {Loupe} from './styles'
You do not create it in the guide
At the end of the guide:
// src / components / Header / index.js
Amounts:
import Nav from '../Nav'
Even this folder, i do not understand where you take it, you do not create it in the guide.
When I saw your ocean-artup project I understood everything that was missing
Unfortunately, even by implementing the missing files and folders, in my gatsby-react project I was not able to make algolia work.
I think I said everything or maybe not.
I hope to be of help to optimize this guide.
Although I found several problems, it was still useful to understand some gatsby structure.
I hope to be of help to optimize this guide. Although I found several problems, it was still useful to understand some gatsby structure.
Glad to hear it! And thanks a lot for your suggestions for improving the post.
Of course, I filled out those fields by entering them directly in gatsby-config or by editing .env.example.
In that case I'm guessing the Contentful space you specified doesn't have any entries of type page
.
I think you might have a much easier time pulling my own site janosh.io and running that locally. Here's the repo. It uses the exact same search component but doesn't rely on Contentful. Instead all content is part of the repo.
There are folders and styles which you do not explain in the guide
import Input from './Input' import * as hitComps from './hits'
I did give the code for the Input
component at the very end of the post. Perhaps you overlooked it. I moved it further up now and added a few lines on how the ./hits.js
file bundles all hit component exports.
Then create a file with the style, but do not give it a name and explain where to insert it:
Good catch. I added the path to the styles.js
file.
Then create the file: // src / components / Search / SearchBox.js New problem about this "./styles":
import {Loupe} from './styles'
You do not create it in the guide
All styled components including SearchIcon
are defined in the same file styles.js
.
At the end of the guide: // src / components / Header / index.js Amounts: import Nav from '../Nav' Even this folder, i do not understand where you take it, you do not create it in the guide.
Well, your Header
component might be completely different from mine and it's unrelated to Algolia and the Search
component so I'm not sure it belongs in that post. But if looking at the code directly in the repo helped clear things up then I guess that's settled anyway.
Let me know if you still need help.
Thanks for your suggestions,
I did give the code for the Input component at the very end of the post. Perhaps you overlooked it. I moved it further up now and added a few lines on how the
./hits.js
file bundles all hit component exports.
Well now it is clearer, I will try soon to follow all the steps and try again.
Well, your Header component might be completely different from mine and it's unrelated to Algolia and the Search component so I'm not sure it belongs in that post. But if looking at the code directly in the repo helped clear things up then I guess that's settled anyway.
Well, I understand what you mean, but a totally inexperienced person of react (like me) copy and paste your code with that import, which compromises the operation of everything, and reading the guide can not find a solution.
For example, I'm trying to use gatsby-starter-ghost
and I do not have any folders called Nav
, my header I think is in components/common/layout.js
I think you might have a much easier time pulling my own site janosh.io and running that locally. Here's the repo. It uses the exact same search component but doesn't rely on Contentful. Instead all content is part of the repo.
Thanks for this, it could help me a lot, but I tried both this way: clone -> yarn -> gatsby develop
, which modifying the .env file and trying again ..
I always find this error:
TypeError: Cannot read property 'edges' of null
IndexPage
C:/Users/****/Documents/REACT/janosh.io/src/pages/index.js:10
7 | import LandingTitle from '../components/LandingTitle'
8 |
9 | const IndexPage = ({ data: { photos, me }, location }) => (
> 10 | <Global margin="0" transparent path={location.pathname}>
11 | <Slideshow>
12 | {photos.edges.map(({ node }) => (
13 | <Img key={node.name} fluid={node.img.fluid} alt={node.name} /
Correct me if I am wrong (I never used Algolia before, so behaviour I discovered might be expected), but isn't @janosh's way of doing search produces 3x more queries than it should? Example @Haroenv gave have 1 query on network tab with any input change and @janosh one have 3. Is this intended? I assume it's not, can someone with a knowledge inspect this?
@JohnatanNorman, if I remember it correctly, the demo of @janosh has multiple indices, and is searching through them separately. That thus will do multiple requests. It's possible to concatenate those in a single network request, but it will still count as a single query.
if I remember it correctly, the demo of @janosh has multiple indices, and is searching through them separately.
That's correct.
Got it, thanks!
Actually, I have 1 more question for @janosh. On your own blog (https://janosh.io) if you click, for example, dark mode button there is an algolia request? Is that intended too?
@JohnatanNorman Wow, thanks for pointing that out. That's definitely unintended! I have a deadline on the 23rd but I'll try to investigate it after that.
@JohnatanNorman Actually, it may be due to React having to update much of the component tree because changing the dark mode setting changes the styled component theme provider at the top the tree. And I guess that request might be auto-fired by the Algolia-connected search input everytime it mounts/updates.
Do you know if that could be true, @Haroenv?
@janosh no problem! I found out your tutorial in google, and tried to implement Algolia consulting your tutorial and documentation. After implementing it I noticed small lag when I open my navigation: it was doing the same thing - firing algolia requests. I thought it was exclusively my problem, and checked your site - the same thing. I think you are probably right about mounting/updates.
yes, request is done every time it mounts. You can fix that issue by making sure you don't recreate the searchClient
Nice. This is indeed solves the problem.
const searchClient = useMemo(
() => algoliasearch(
process.env.GATSBY_ALGOLIA_APP_ID,
process.env.GATSBY_ALGOLIA_SEARCH_KEY
), []
)
Hi,
I hope this is the platform where someone could point me in the right direction. I'm following the guide here
Everything works perfectly, except when suggestion is chosen/clicked, it doesn't go to the article but the homepage instead.
I'm kinda of lost..
import React, { Component } from 'react'
import { navigate } from 'gatsby'
import './SearchBox.css'
let algoliasearch, autocomplete, client, index
if (typeof window !== 'undefined') {
algoliasearch = require('algoliasearch/lite')
autocomplete = require('autocomplete.js')
client = algoliasearch(
process.env.GATSBY_ALGOLIA_APP_ID,
process.env.GATSBY_ALGOLIA_SEARCH_API_KEY
)
index = client.initIndex(process.env.GATSBY_ALGOLIA_INDEX_NAME)
}
class SearchBox extends Component {
componentDidMount() {
if (typeof window === 'undefined') {
return
}
autocomplete('#algolia-search-input', { hint: false }, [
{
source: autocomplete.sources.hits(index, { hitsPerPage: 5 }),
displayKey: 'title',
templates: {
suggestion: function({ _highlightResult: { title, description } }) {
return `
<p class="title">${title.value}</p>
<p class="description">${description.value}</p>
`
},
footer:
'<div class="branding">Powered by <img src="https://www.algolia.com/static_assets/images/press/downloads/algolia-logo-light.svg" /></div>',
},
},
]).on('autocomplete:selected', function(
event,
suggestion,
dataset,
context
) {
navigate(suggestion.url)
})
}
render() {
return (
<div style={{ marginBottom: '1rem' }}>
<input
type="search"
id="algolia-search-input"
placeholder="Search"
/>
</div>
)
}
}
export default SearchBox
Does the suggestion actually have a url? You should log that out to verify
@Haroenv That's what I've been trying to find out. The console log doesn't have the url, neither do the repo where the guide is written. I'm assuming that the url is generated automatically. If it is not, where do I set the url?
Thanks for the response, though ;)
the should be something you add to the index yourself @yansusanto, it's not done automatically. Likely you can craft it based on the data you have requested in the queries.
Turn it into "url" directly in the query, or use tranformItems to help
Thanks, @Haroenv. Although I have no clue how it should be done, I'll give it a try. The repo here doesn't set the url too so I'm not sure how it is done.
here you need to make the url from the slug: https://github.com/eunjae-lee/gatsby-starter-blog-with-algolia/blob/master/gatsby-plugin-algolia-config.js#L35
Yes, that's what I have on my config file. The exact same code.
Ah, I got it. It should be navigate(suggestion.path)
and not navigate(suggestion.url)
. Thanks, @Haroenv for the help. Appreciate it!
@yansusanto Hey, I was just about to answer you. There must be a bug in my code. Sorry for inconvenience. I've updated it on the repo and the blog post.
Perfect! I'll lock this issue for now, please create new issues in the future instead of commenting on a closed one :)
Good evening, I'm trying to use gatsby-algolia I downloaded this project, inserting my parameters of algolia and launching
gatsby build
, can successfully connect to Algolia.I would like an example with gatsby to see the results in the frontend, instantsearch or autocomplete. At the moment if I start gatsby development, the pages start correctly, but I do not see the algolia data or a search. Is there a working example from which to start? Thank you