Facebook pixel form submission tracking on gatsbyjs - reactjs

I'm trying to find a way on Gatsbyjs site to add custom Facebook pixel conversion when visitors submit the contact form. Couldn't figure it out even using facebook pixel documentation.
The plugin that I'm using - https://github.com/gabefromutah/gatsby-plugin-facebook-pixel
The event that I need to track is:
fbq('track', 'Lead', {content_name: 'ContactForm'});
Is it the best way to do it through button click on the contact form? If so, how do I add it in?
Any help would be appreciated. Thanks

This plugin (gatsby-plugin-facebook-pixel) only works in production build (i.e gatsby build && gatsby serve), perhaps that's why you're not seeing any tracking?
It sounds like you only want to track successful submission? If so, you might want to avoid only tracking button click and instead track after the submission's been received. For example, if you're using fetch to send your data, it might look roughly like so:
const submitHandler = (data) => fetch(url, {
method: 'POST',
body: JSON.stringify(data)
})
.then(res => res.json())
.then(res => {
if (res.ok) {
fbq('track', ...)
}
})
.catch(err => ...)

Related

Chrome and Edge hang on React page load for only some users, should I change my useEffect strategy?

My ReactJS project displays a simple page consisting of a header section with project title, version and a few nav links, then a table of about 200 results as the main content of the page.
The initial page loads for everyone and the components appear as expected, but on page load (I believe this is when the useEffect hook kicks in) some users report the page becoming un-responsive and no matter how long it is left, it never finishes. This has been reported in both Chrome and Edge by 5 different users across a site of 200+ users, the majority have no issues despite running the exact same hardware and connection.
On page load, I expect the title, version and table contents (plus a few other variables) to be populated and automatically updated since these are in state, and for most users, this works as expected.
Below is my useEffect()
useEffect(() => {
// Update all initial values
fetchLastUpdated();
fetchVersion();
fetchUsername();
fetchUpcomingFilterOptions();
fetchLongCustomerNames();
fetchConfigs();
fetchUpcomingResults() // This will be displayed as rows
const job = document.getElementById("job")
if ( !!job ) {
job.addEventListener("keyup", function(event) {
if (event.key === "Enter") {
submitForm()
}
});
}
// Find environment for API links: testing/pre-release, testing/QA, flx
const url = window.location.href
if ( url.includes('localhost') ) {
setEnvironment("testing/pre-release")
} else if ( url.includes('testing/pre-release') ) {
setEnvironment("testing/pre-release")
} else if ( url.includes('testing/QA') ) {
setEnvironment("testing/QA")
} else if ( url.includes('flx') ) {
setEnvironment("flx")
}
}, [])
Below an example of an API call from useEffect
const fetchConfigs = () => {
axios({
method: "get",
url: "http://myURL/" + environment + "/WITracker/public/api/myConfigs",
config: { headers: {
'Access-Control-Allow-Origin': '*',
"Content-Type": "multipart/form-data"
}}
})
.then(function (response) {
setConfigs(response.data);
})
.catch(function (response) {
console.log("Failed to fetch configs!");
addNotification("Unable to fetch configs", "Retry in progress...")
})
}
When remote accessing the users with troubles loading the page, I asked that they each try the alternative browser: Chrome -> Edge or Edge -> Chrome and in each case this resolved the issue. I found this strange as I would have expected the same browser to be causing the same behaviour each time across the users.
I would like to make sure that the page reliably loads for all users regardless of their browser preference. I'm at a bit of a loss trying to find out why only some users are getting unresponsive errors so any possible solutions or suggestions of what to try are welcome!
Possible workaround?
I'm not sure that I have set up my useEffect the correct way using best practices. I'm thinking of adding a slight delay to the API calls, since the page loads the components without issue, and once the delay is up, to synchronously make each of the calls, giving the browser more of a chance to process the smaller chunks of work rather than all at once... please can somebody let me know their thoughts on this?
e.g. Something similar to the below theory?
useEffect(async () => {
// Some delay here, with loading screen
wait(1000) //custom function to wait?
// ...then, update all initial values
await fetchLastUpdated();
await fetchVersion();
await fetchUsername();
await fetchUpcomingFilterOptions();
await fetchLongCustomerNames();
await fetchConfigs();
await fetchUpcomingResults()
...
Thanks in advance

Checkout page blank before going to payment method url in react project

Hi I am developing an ecommerce site. here I suffer this problem:
Suppose I have an array of product I want to map over the array and hit an post api for all array of items. When all array of items will be post. then I will call another api for getting response.I want to call second api only if the array of elements posted to api.
here is my code :
I am showing all cart items in checkout page. when user want to pay online payment. I place an order and i am getting getway url. I have to clean the cart right? but when my cart cleared the checkout page appearing blank, afer some millisecond page redirect to the gateway URL. I want that after redirect cart will be cleared because if user see blank page it is not good UX.
```await getData(${REST_BASE_API_URL}/mobileapps/orders/${order_id}, {}, userToken())
.then(res => {
let increment_id = res?.increment_id;
if (paymentMethod === 'sslcommerz') {
// navigate('/order-success');
let url = `anything`;
getData(url, {}, userToken())
.then(res => {
window.location.href = res; //redirect to gateway url
dispatch(saveUpdatedCart([])); //cart clear
clearCartAfterOrder(); //set new cart id in redux
console.log('ssl_res', res)
})
.catch(err => {
console.log(err)
})```

update state of the parent screen if an update occurs in current screen

I am using react-navigation 6 and react-native CLI, to make a chat application. I want to achieve this feature which is common in every chat application that when we send a message to someone, and go back to homescreen of the app (where all conversations are listed), the last message sent, can be seen.
Like if I sent message and pressed the back button, it will navigate me to home screen where all my conversations are, and it should update the conversation where I sent the message.
I have tried route.params, but it gives a warning that non-serializable values found.
React navigation warning
Also, I have heard that passing setState function to child component is very bad practice as it is mentioned here
I also tried navigation_events along with useEffect , this was a surprise to me that it didn't work either.
When I refresh the screen manually, or logout and log in, then it refreshes completely, but doesn't when I go back from application.
React.useEffect(() => {
navigation.addListener('focus', e => {
fetchConvos();
});
return () => {};
}, []); //also tried [navigation] instead of []
const fetchConvos = () => {
fetch('http://localhost:15000/' + id + '/conversations', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
redirect: 'follow',
referrerPolicy: 'no-referrer',
})
.then(res => res.json())
.then(received => {
if (received?.response !== false) {
setConversations(received);
}
});
};
I have checked the id , received and even setConversations, they all are updating, but my screen still rendering the old messages.
Also, I don't want to use Async Storage or redux for this simple problem like this.
I can share the complete code if this isn't enough.
EDIT
I figured out one more way to update it may help clarify the situation more.
React.useEffect(() => {
navigation.addListener('focus', e => {
setConversations([]); //first setting convos to empty
fetchConvos(); //then fetching new data
});
return () => {};
}, []);
But this method is quite slow as I am updating the state of conversations twice.
I would appreciate if someone can help me here.
By taking the last 2 samples of code, I'd go down the route of setting the state to change the data. Like, I don't know the structure of your code completely. But i'm assuming you're using useEffect inside some component, right? In that case, React Context might be what you're looking for:
How to use react hooks on react-native with react-navigation
It allows to share informations, without having to build a structured store like redux. You should probably working on redesign a bit the code as, if you're following the current logic, you're going to split data pool of the conversation in the menu and load them when the "back" navigation event occurs, right?
Whilst the conversation data should be shared and available to both components, regardless where you're.
At least I'd rethink it this way to allow consistent data throughout the whole application.
Unless you've to do something specific and on-spot, of course.

How can I post form data from react to an express.js server and use it as part of a url string

Just to make this clearer. I have a form where the user inputs a name which is passed to the apiUrl const to become part of the URL string. The form input data is passed through state as {this.state.input}. After the user inputs the form with the name he wants to search for, he clicks a button which calls the onButtonSubmit function that fetches the data with the updated apiUrl parameters. The catch is, this is running on the front-end and as this is a proprietary api, I don't want to expose the api key (which is part of the url) to the user.
I have set up an express.js server but I'm still unsure on how I can post the form data to it and then use that in the same manner used in my code below.
onButtonSubmit = () => {
const apiUrl = 'URLStringPart1' + this.state.input + 'URLStringpart2withAPIKey';
fetch(apiUrl)
.then(res => res.json())
.then(
result => {
this.setState({
isLoaded: true,
array1: result.array1,
array2: result.array2,
array3: result.array3,
array4: result.array4,
array5: result.array5,
route: 'fetched'
});
},
error => {
this.setState({
isLoaded: false,
error: error
});
}
);
}
So the output I'm looking for would follow something like this:
Post form data from frontend after the user submits it with a
button click
Through the backend, after the form data is posted, use it to update the apiurl and then fetch the data from the api(using axios perhaps)
Send the fetched data back to the frontend
I think you need to use prams, in your express server the API route should look like this: api/users/:name --> returns user with this name.
Then try fetching this API by sending the request to the server like this:
http://locahost:8000/api/users/${this.state.name}

React-table. how to set the width of columns after receiving them from the server (fetch request)

I saved data to the server after resize columns, and then after reloading browser page I try to set the column width - which I got from server/
I tried from this example but not successfully
Can you please give me example how correctly do this?
p.s sorry about my English . I hope I said clearly
added chunk of my code
useEffect(() => {
....
fetch(url, requestOptions)
.then((response) => response.json())
.then((data) =>
console.log(">>>WIDTH>>>", data.columnResizing); // here is ok - I got for example {name: 255}
setResizeColumns(data.columnResizing); // my own func setResizeColumns
})
....
Currently no direct apis exists for this, try to make use of action at https://github.com/tannerlinsley/react-table/blob/master/src/plugin-hooks/useResizeColumns.js#L203

Resources